AES加密算法在linux下解密失败,windows下成功的问题
1 package com.more; 2 3 4 import java.security.NoSuchAlgorithmException; 5 import java.security.SecureRandom; 6 import javax.crypto.Cipher; 7 import javax.crypto.KeyGenerator; 8 import javax.crypto.SecretKey; 9 import javax.crypto.spec.SecretKeySpec; 10 import org.apache.commons.codec.binary.Base64; 11 12 public class AESUtil 13 { 14 public static String encrypt(String content, String password) 15 { 16 try 17 { 18 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 19 20 byte[] byteContent = content.getBytes("utf-8"); 21 SecretKeySpec secreKeySpec = getSecretKey(password); 22 cipher.init(1, secreKeySpec); 23 24 byte[] result = cipher.doFinal(byteContent); 25 26 return Base64.encodeBase64String(result); 27 } 28 catch (Exception ex) 29 { 30 ex.printStackTrace(); 31 } 32 return null; 33 } 34 35 public static String decrypt(String content, String password) 36 { 37 try 38 { 39 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 40 41 42 cipher.init(2, getSecretKey(password)); 43 44 45 byte[] result = cipher.doFinal(Base64.decodeBase64(content)); 46 47 return new String(result, "utf-8"); 48 } 49 catch (Exception ex) 50 { 51 ex.printStackTrace(); 52 } 53 return null; 54 } 55 56 private static SecretKeySpec getSecretKey(String password) 57 { 58 KeyGenerator kg = null; 59 try 60 { 61 kg = KeyGenerator.getInstance("AES"); 62 63 SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 64 secureRandom.setSeed(password.getBytes()); 65 66 kg.init(128, secureRandom); 67 68 69 SecretKey secretKey = kg.generateKey(); 70 71 return new SecretKeySpec(secretKey.getEncoded(), "AES"); 72 } 73 catch (NoSuchAlgorithmException ex) 74 { 75 ex.printStackTrace(); 76 } 77 return null; 78 } 79 }
在linux系统下抛出异常:javax.crypto.BadPaddingException: Given final block not properly padded。
在工具类中增加调用了 setSeed 方法。
原因分析
SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法之后又调用了 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。
文章解决方式来源于:https://m.jb51.net/article/40941.htm