Java中的AES解密--IvParameterSpec太大了

时间:2012-10-24 10:55:10

标签: java encryption aes

我打算用两把钥匙解密明文。

如图所示,我们有一个加密文件,其中包含KEY1(128字节),KEYIV(128字节),key2(128字节) - 在这种情况下不使用 - 和密文。

descriptive image

我得到的错误是:

Exception in thread "main" java.security.InvalidAlgorithmParameterException: 
Wrong IV length: must be 16 bytes long.

但它是64字节。

public class AES {
 public static void main(String[] args) throws Exception {

  byte[] encKey1 = new byte[128];

  byte[] EncIV = new byte[256];
  byte[] UnEncIV = new byte[128];
  byte[] unCrypKey = new byte[128];
  byte[] unCrypText = new byte[1424];

  File f = new File("C://ftp//ciphertext.enc");
  FileInputStream fis = new FileInputStream(F);
  byte[] EncText = new byte[(int) f.length()];
  fis.read(encKey1);
  fis.read(EncIV);
  fis.read(EncText);
  EncIV = Arrays.copyOfRange(EncIV, 128, 256);
  EncText = Arrays.copyOfRange(EncText, 384, EncText.length);
  System.out.println(EncText.length);
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  char[] password = "lab1StorePass".toCharArray();
  java.io.FileInputStream fos = new java.io.FileInputStream(
    "C://ftp//lab1Store");
  ks.load(fos, password);

  char[] passwordkey1 = "lab1KeyPass".toCharArray();

  PrivateKey Lab1EncKey = (PrivateKey) ks.getKey("lab1EncKeys",
    passwordkey1);

  Cipher rsaDec = Cipher.getInstance("RSA"); // set cipher to RSA decryption
  rsaDec.init(Cipher.DECRYPT_MODE, Lab1EncKey); // initalize cipher ti lab1key

  unCrypKey = rsaDec.doFinal(encKey1); // Decryps first key

  UnEncIV = rsaDec.doFinal(EncIV); //decryps encive byte array to undecrypted bytearray---- OBS! Error this is 64 BYTES big, we want 16?
  System.out.println("lab1key "+ unCrypKey +" IV " + UnEncIV);
  //-------CIPHERTEXT decryption---------
  Cipher AESDec = Cipher.getInstance("AES/CBC/PKCS5Padding");
  //---------convert decrypted bytearrays to acctual keys
  SecretKeySpec unCrypKey1 = new SecretKeySpec(unCrypKey, "AES");
  IvParameterSpec ivSpec = new IvParameterSpec(UnEncIV);

  AESDec.init(Cipher.DECRYPT_MODE, unCrypKey1, ivSpec );

  unCrypText = AESDec.doFinal(EncText);

  // Convert decrypted cipher bytearray to string
  String deCryptedString = new String(unCrypKey);
  System.out.println(deCryptedString);
 }

1 个答案:

答案 0 :(得分:2)

由于位和字节之间的混淆,您的数组完全错误。你的IV实际上是256字节长,而不是64字节,即使应用程序超过了它,它也会抱怨128字节密钥。 AES是128位密码,使用128位到256 密钥。它应该看起来更像是这样:

byte[] encKey1 = new byte[16];
byte[] EncIV = new byte[16];
byte[] UnEncIV = new byte[16];
byte[] unCrypKey = new byte[16];

另一个潜在的错误是unCrypText的定义,它应该是:

byte[] unCrypText = new byte[(int) f.length()];

就像EncText一样,但这可能与测试无关。