1

我将使用两个密钥解密明文。

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

描述性图像

我在这里得到的错误是:

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);
 }
4

1 回答 1

2

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

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 一样,但这对于测试可能无关紧要。

于 2012-10-26T01:20:50.733 回答