使用32字节密钥的Java AES加密-密钥大小无效
可能重复:使用32字节密钥的Java AES加密-密钥大小无效,java,encryption,aes,Java,Encryption,Aes,可能重复: 公共静态字节[]加密字节(字节[]字节,字节[]密钥) { 密码=空; 尝试 { cipher=cipher.getInstance(“AES/ECB/PKCS5Padding”); SecretKeySpec secretKey=新SecretKeySpec(键,“AES”); cipher.init(cipher.ENCRYPT_模式,secretKey); 返回Base64.encodeBase64(cipher.doFinal(字节)); } 捕获(例外e) { e、 pr
公共静态字节[]加密字节(字节[]字节,字节[]密钥)
{
密码=空;
尝试
{
cipher=cipher.getInstance(“AES/ECB/PKCS5Padding”);
SecretKeySpec secretKey=新SecretKeySpec(键,“AES”);
cipher.init(cipher.ENCRYPT_模式,secretKey);
返回Base64.encodeBase64(cipher.doFinal(字节));
}
捕获(例外e)
{
e、 printStackTrace();
}
返回null;
}
公共静态字节[]DecrypytBytes(字节[]encryptedData,字符串密钥)
{
byte[]keyBytes=convertToByteArray(键);
密码=空;
尝试
{
cipher=cipher.getInstance(“AES/ECB/PKCS5PADDING”);
SecretKeySpec secretKey=新SecretKeySpec(keyBytes,“AES”);
cipher.init(cipher.DECRYPT_模式,secretKey);
返回cipher.doFinal(Base64.decodeBase64(encryptedData));
}
捕获(例外e)
{
e、 printStackTrace();
}
返回null;
}
//只需每隔两个字符将它们转换为一个字节值
//然后把它们塞进一个过道
公共静态字节[]convertToByteArray(字符串键)
{
byte[]b=新字节[key.length()/2];
对于(inti=0,bStepper=0;i
“事实证明,密码类通常不允许密钥大小超过128位的加密。这背后的明显原因是,一些国家(尽管越来越少)对进口加密软件的允许密钥强度有限制,尽管实际数字128有疑问(见下文).好消息是:
通过使用Sun提供的其他安全策略文件覆盖安全策略文件,您可以轻松删除该限制。“您安装了吗?这就是问题所在。感谢您的回复
public static byte[] encryptBytes(byte[] bytes, byte[] key)
{
Cipher cipher = null;
try
{
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.encodeBase64(cipher.doFinal(bytes));
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static byte[] decrpytBytes(byte[] encryptedData, String key)
{
byte[] keyBytes = convertToByteArray(key);
Cipher cipher = null;
try
{
cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(Base64.decodeBase64(encryptedData));
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
//Simply takes every other two characters an terms them into a byte value
//then stuffs them into a byteArray
public static byte[] convertToByteArray(String key)
{
byte[] b = new byte[key.length()/2];
for(int i=0, bStepper=0; i<key.length()+2; i+=2)
if(i !=0)
b[bStepper++]=((byte) Integer.parseInt((key.charAt(i-2)+""+key.charAt(i-1)), 16));
return b;
}
public static void main(String[] args) throws Exception
{
//This string has 64 characters. When sent to convertToByteArray it returns a byte array or 32 bytes
String key = "00112233445566778899AABBCCDDEEFF0123456789ABCDEF0123456789ABCDEF";
//Test it out
byte f[] = {2,4,7};
byte[] encrypted = encryptBytes(f, convertToByteArray(key));
byte[] unencrypted = decrpytBytes(encrypted, key);
System.out.print(unencrypted[0]);
}