代码之家  ›  专栏  ›  技术社区  ›  Vladimir

使用第三方Java库实现AES加密,无需美国法律限制

  •  2
  • Vladimir  · 技术社区  · 15 年前

    我使用特定的Java工具和BooCyCaseAdvor为特定的AES算法实现了具有特定任务特定参数的AES加密。

    代码如下:

    private byte[] aesEncryptedInfo(String info) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidParameterSpecException, InvalidAlgorithmParameterException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        SecretKey secret = new SecretKeySpec(CUSTOMLONGSECRETKEY.substring(0, 32).getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(VECTOR_SECRET_KEY.getBytes()));
        return cipher.doFinal(info.getBytes("UTF-8"));
    }
    

    在某些环境中,此代码需要特殊的策略文件。参见相关问题: InvalidKeyException Illegal key size

    我的目标是使用第三方库重新实现它,理想情况下我将使用已经用作提供者的BouncyCastle。该库不应该对标准Java策略文件进行删除。换句话说,不应该有任何限制。

    请在您的答案中建议如何使用BouncyCastle或其他第三方库重新实现它,这些库可以不受上述限制地工作。理想情况下,我会看到代码:—)

    非常感谢你的阅读!

    经过一段时间的耽搁,我现在很乐意发布一个解决方案。希望有人能从中受益,因为BouncyCastle文档中没有很多示例:—)

    private byte[] aesEncryptedInfo(String info)
    // Creating AES/CBC/PKCS7Padding cipher with specified Secret Key and Initial Vector
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    cipher.init(true, new ParametersWithIV(new KeyParameter(CUSTOMLONGSECRETKEY.getBytes()), VECTOR_SECRET_KEY.getBytes()));
    
    byte[] inputData = info.getBytes("UTF-8");
    int outBlockSize = cipher.getOutputSize(inputData.length);
    byte[] outputData = new byte[outBlockSize];
    
    int outLength = cipher.processBytes(inputData, 0, inputData.length, outputData, 0);
    outLength += cipher.doFinal(outputData, outLength);
    if (outLength != outBlockSize) {
        return Arrays.copyOf(outputData, outLength);
    }
    else {
        return outputData;
    }    
    

    }

    顺便说一下,我发现Java API和PosiCype API之间有两个不同点: 1。BouncyCastle使用对象组合来创建所需的密码。而Java API使用字符串来标识需要的密码。 2。BC加密代码稍大一些,而Java API代码更紧凑。

    解决方案是完全替换原来的Java API实现——证明是我做的一个定制单元测试。

    3 回复  |  直到 13 年前
        1
  •  3
  •   President James K. Polk    15 年前

    org.bouncycastle.* Cipher KeyGenerator

    AESEngine javadocs for the bouncycastle

        2
  •  1
  •   soc Bhuwan Tripathi    15 年前

        3
  •  0
  •   dekz    15 年前
    推荐文章