package testAES
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.base64;
@Compon
ent
public class AesUtils {
private static final String SECRET = "AES";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null){
Security.addProvider(new BouncyCastleProvider());
}
}
public static String AESECBPkcs7PaddingEncrypt(String str, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
return new String(base64.getEncoder().encode(doFinal));
}
public static String AESECBPkcs7PaddingDecrypt(String str, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
byte[] doFinal = cipher.doFinal(base64.getDecoder().decode(str));
return new String(doFinal);
}
public static void main(String[] args) throws Exception {
String str = "12345678";
String key = "1234123412341234";
System.out.println("原始字符串:" + str);
String encryptStr = AESECBPkcs7PaddingEncrypt(str, key);
System.out.println("加密字符串:" + encryptStr);
String decryptStr = AESECBPkcs7PaddingDecrypt(encryptStr, key);
System.out.println("解密字符串:" + decryptStr);
}
}
若找不到bouncycastle包,可以添加maven依赖
org.bouncycastle bcprov-jdk16 1.46
参考内容
http://www.10qianwan.com/articledetail/651897.html
https://blog.csdn.net/lyjilu2008/article/details/84733762



