尝试理解在标记重复之前:InvalidKeyException:非法的密钥大小

时间:2017-09-22 10:25:43

标签: java arrays encryption aes decoding

实际上我得到的是InvalidKeyException:非法的密钥大小,但是相同的代码在生产中正在运行。当我尝试在本地运行此代码时,我在下面的行中解码时面临密钥大小问题:

 cipher.init(2, new SecretKeySpec(secretKey, "AES"), new IvParameterSpec(initVector));

在上面一行我得到以下异常:

 public byte[] getPageByteStream(String fileName)
    throws DMSApplicationException
  {
    logger.info(GridFsPagesDAOImpl.class + " Entering in to getPageByteStream DAO Method : " + fileName);

    Query searchQuery = new Query(Criteria.where("filename").is(fileName));
    GridFSDBFile gridFSDBFile = DmsDBUtils.getGridFsOperations().findOne(searchQuery);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    byte[] results = null;
    byte[] initVector = null;
    try {
      gridFSDBFile.writeTo(stream);
      byte[] bytes = null;
      bytes = stream.toByteArray();
      Base64 base64 = new Base64();
      byte[] decodedArr = base64.decode(bytes);
      byte[] decArr = Arrays.copyOfRange(decodedArr, 24, bytes.length);
    byte[] secretKey = base64.decode("mkJmh3d2WLNXgmWIv4znTU+IXk7XczlInO9mXmv1iBE=\n");
     String str = new String(secretKey, "UTF-8");
     System.out.println("decodes string :  "+str);
     Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      initVector = Arrays.copyOfRange(decodedArr, 8, 24);

      cipher.init(2, new SecretKeySpec(secretKey, "AES"), new IvParameterSpec(initVector));
      decArr = Arrays.copyOfRange(decodedArr, 24, bytes.length);
      byte[] decArr1 = Arrays.copyOfRange(decArr, 0, decArr.length - decArr.length % 16);

      results = cipher.doFinal(decArr1);

    } catch (Exception e) {
      e.printStackTrace();
      logger.info(GridFsPagesDAOImpl.class + " Exiting from getPageByteStream DAO Method " + e);


      if (gridFSDBFile != null) {
        try {
          stream.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    }
    finally
    {
      if (gridFSDBFile != null) {
        try {
          stream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    logger.info(GridFsPagesDAOImpl.class + " Exiting from getPageByteStream DAO Method " + fileName);
    return results;
  }
}
你能建议我吗?

帮助非常明显。

1 个答案:

答案 0 :(得分:1)

看起来你正在使用带有256位密钥的AES。

您需要安装Java Cryptography Extension(JCE)Unlimited Strength Jurisdiction Policy文件才能使用大于128位的密钥。

http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html