使用J2ME中的Bouncycastle示例进行AES加密/解密

Mih*_*ala 4 encryption bouncycastle aes java-me

我想使用带有弹性城堡的AES算法在J2ME中加密和解密数据可以任何人给我示例代码

我想使用ECB和PKCS5Padding

提前致谢.

Jam*_*olk 19

我确信有一些例子,但我没有找到它们.以下是一些帮助您入门的提示.您需要学习如何将BC类连接在一起.首先,获取bouncycastle源代码,并准备好在遇到问题时查看它.它实际上非常易读,所以当文档很差时不要害怕检查它.例如,许多类需要CipherParameters对象的实例,但文档很少指定任何更多细节.但是,在源代码中,很明显可以预期哪些实现类.

例如AESEngine,选择一个AES引擎作为加密引擎.接下来选一个模式; ECB很少是正确的,例如,如果您选择CBC模式,CBCBlockCipher则从AESEngine对象创建一个对象.接下来,使用此对象创建一个PaddedBufferBlockCipher对象.默认构造函数使用PKCS7填充,它与您想要的PKCS5填充相同.现在您需要创建一个对象来保存密钥和IV.这是CipherParameters界面.您可以分两步创建对象.首先,KeyParameter使用密钥创建对象.接下来,ParametersWithIV使用KeyParameter对象和IV 创建一个对象.此对象提供给对象的init方法,PaddedBufferBlockCipher然后您就可以开始使用了.

编辑

这是一个小例子:

private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
        throws Exception
{
    int minSize = cipher.getOutputSize(data.length);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    int actualLength = length1 + length2;
    byte[] result = new byte[actualLength];
    System.arraycopy(outBuf, 0, result, 0, result.length);
    return result;
}

private static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception
{
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
            new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
    aes.init(false, ivAndKey);
    return cipherData(aes, cipher);
}

private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
            new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
    aes.init(true, ivAndKey);
    return cipherData(aes, plain);
}
Run Code Online (Sandbox Code Playgroud)

  • 下面是一个解释:[初始化向量(https://secure.wikimedia.org/wikipedia/en/wiki/Block_cipher_modes_of_operation#Initialization_vector_.28IV.29) (2认同)