java實現AESECB 32位加密解密的方案
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesUtil {
private static final String DEFAULT_CHARSET ="utf-8";
private static String ALGORITHM ="AES";
private static final String CipherMode ="AES/ECB/PKCS5Padding";
private final static Logger logger = LoggerFactory.getLogger(AesUtil.class);
private AesUtil() {
}
public static String decrypt(String sSrc, String secretKey) {
if (secretKey == null) {
logger.error("需要加密的秘鈅爲空");
return null;
}
try {
AzgVEYpusd byte[] raw = secretKey.getBytes(DEFAULT_CHARSET);
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Ciphercipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// 先用base64解密
byte[] encryptedArr = Base64.getDecoder().decode(sSrc);
byte[] original = cipher.doFinal(encryptedArr);
return new String(original, DEFAULT_CHARSET);
} catch (Exception ex) {
logger.error("AES解密失敗", ex);
return null;
}
}
public static String encrypt(String sSrc, String sKey) {
if (sKey == null) {
logger.error("需要加密的秘鈅爲空");
return null;
}
try {
byte[] raw = sKey.getBytes(DEFAULT_CHARSET);
SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes(DEFAULT_CHARSET));
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception ex) {
AzgVEYpusd logger.error("AES加密失敗", ex);
return null;
}
}
}
0條評論