Java实现AES加密解密

r囧r小猫 2023-06-16 14:59 89阅读 0赞

之前常用两种加密算法:Base64和Md5,前者容易破解,后者不可逆。

AES采用对称加密方式,破解难度非常大,在可逆的基础上,能很好的保证数据的安全性。

这里介绍Java中实现AES加密算法的加密与解密实现:

  1. import org.apache.commons.codec.binary.Base64;
  2. import org.apache.commons.codec.binary.Hex;
  3. import org.springframework.util.Base64Utils;
  4. import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
  5. import javax.crypto.*;
  6. import javax.crypto.spec.SecretKeySpec;
  7. import java.io.UnsupportedEncodingException;
  8. import java.security.Key;
  9. import java.security.NoSuchAlgorithmException;
  10. import java.security.SecureRandom;
  11. public class AesUtil {
  12. public static void main(String[] args) throws UnsupportedEncodingException {
  13. for (int i = 0; i < 10; i ) {
  14. String key = generateKey(); // 提前生成的一个key
  15. String ps = encode(key, "123");
  16. System.out.println("加密: " ps);
  17. String res = decode(key, ps);
  18. System.out.println("解密: " res);
  19. }
  20. }
  21. /** * 生成key * @return */
  22. public static String generateKey() {
  23. try {
  24. KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
  25. keyGenerator.init(new SecureRandom());
  26. SecretKey secretKey = keyGenerator.generateKey();
  27. byte[] byteKey = secretKey.getEncoded();
  28. return Hex.encodeHexString(byteKey);
  29. } catch (NoSuchAlgorithmException e) {
  30. e.printStackTrace();
  31. }
  32. return null;
  33. }
  34. /** * AES加密 * @param thisKey * @param data * @return */
  35. public static String encode(String thisKey, String data) {
  36. try {
  37. // 转换KEY
  38. Key key = new SecretKeySpec(Hex.decodeHex(thisKey),"AES");
  39. //System.out.println(thisKey);
  40. // 加密
  41. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  42. cipher.init(Cipher.ENCRYPT_MODE, key);
  43. byte[] result = cipher.doFinal(data.getBytes());
  44. return Hex.encodeHexString(result);
  45. } catch (Exception e) {
  46. e.printStackTrace();
  47. }
  48. return null;
  49. }
  50. /** * AES解密 * @param thisKey * @param data * @return */
  51. public static String decode(String thisKey, String data) {
  52. try {
  53. // 转换KEY
  54. Key key = new SecretKeySpec(Hex.decodeHex(thisKey),"AES");
  55. // 解密
  56. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  57. cipher.init(Cipher.DECRYPT_MODE, key);
  58. byte[] result = cipher.doFinal(Hex.decodeHex(data));
  59. return new String(result);
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. return null;
  64. }
  65. }

交流学习

个人网站:http://www.eknown.cn

GitHub:https://github.com/laolunsi

公众号:猿生物语,“分享技术,也感悟人生”,欢迎关注!
watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI4Mzc5ODA5_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,89人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java实现AES加密解密

    之前常用两种加密算法:Base64和Md5,前者容易破解,后者不可逆。 AES采用对称加密方式,破解难度非常大,在可逆的基础上,能很好的保证数据的安全性。 这里介绍Java