2012-10-09 59 views
3

我想使用192位密钥加密数据。Android AES crypt 192bit密钥

SecretKeySpec key = new SecretKeySpec(new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "AES/CBC/NoPadding"); 
byte[] data = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 
byte[] encrypted = null; 
try { 
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    encrypted = cipher.doFinal(data); 
} catch (Exception e) { 
    System.out.println(e.getMessage()); 
} 

但加密是不正确的。而且每次数组的内容都不一样。为什么?

+2

您对“不正确”是什么意思? –

+1

您如何初始化您的KeyGenerator? –

+0

>>你的意思是“不正确” 加密结果与C++中的加密结果不同 >>你如何初始化你的KeyGenerator? 我没有生成密钥。 –

回答

1

您正在使用CBC模式,它需要一个初始化向量(IV)。由于您没有明确设置,每次加密时都会生成随机数。你必须要么:

  • 使用静态IV(不推荐),或
  • 与密文的C++程序

下面是如何设置的IV一起发送IV Java,对于C++,请参阅您正在使用的库的文档:

byte[] iv = generateIv(cipher.getBlockSize()); 
IvParameterSpec ivParams = new IvParameterSpec(iv); 
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);