2017-10-28 437 views
0

我使用新的JDK 9發行版編寫了此類。Java - AES 256可在JDK 7和JDK 9中運行,但不能在JDK 8中運行

public class Encrypters { 
    public static byte[] AESEncrypt(Key key, byte[] data) throws GeneralSecurityException { 
     Cipher cipher=Cipher.getInstance("AES"); 
     cipher.init(Cipher.ENCRYPT_MODE, key); 

     byte[] encryptedData=cipher.doFinal(data); 
     return encryptedData; 
    } 
} 

我也寫了這個輔助類

public class Hashes { 
    public static byte[] sha256Hash(byte[] input) { 
     return hash(input, "SHA-256"); 
    } 

    private static byte[] hash(byte[] input, String algorithm) { 
     MessageDigest md=null; 
     try { 
      md=MessageDigest.getInstance(algorithm); 
     } 
     catch (NoSuchAlgorithmException e) {} 
     return md.digest(input); 
    } 
} 

這是使用加密的字符串:

String password=...; 
String data=...; 
Key key=new SecretKeySpec(Hashes.sha256Hash(password.getBytes(), "AES")); 
Encrypters.AESEncrypt(key, data.getBytes()); 

此代碼與JDK 9和JDK 7上同時運行,但與JDK 8. 如果我嘗試使用JDK 8運行,則出現此錯誤:

java.security.InvalidKeyException: Illegal key size or default parameters 

爲什麼我得到這個錯誤? Java 8不支持AES-256?

+0

它可能不相關,但您應該始終定義密碼的所有方面。不要只使用「AES」。你也不應該使用ECB模式。改爲使用「AES/CBC/PKCS5Padding」。 –

回答

1

它是支持的,你只需要更新Java 8 JRE(link),或包括JCE策略文件(link) 的強加密從未被默認包含在JRE中,它是最新的分佈。在你的情況下,它適用於Java 7的原因可能是因爲它是7u171或更高版本。請參閱 JDK-8170157瞭解有關何時將其回溯到不同版本的詳細信息。