使用RSA加密图像时出错

时间:2012-03-26 17:27:16

标签: java image encryption rsa public-key-encryption

我需要使用RSA加密大小为151 * 15的图像。

这是加密图像文件的java代码

import javax.crypto.Cipher;
plaintext = time;
cipher = Cipher.getInstance('RSA');
keygen = java.security.KeyPairGenerator.getInstance('RSA');
keyPair = keygen.genKeyPair();
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate())

plaintextUnicodeVals = uint16(plaintext)
plaintextBytes = typecast(plaintextUnicodeVals, 'int8')
ciphertext = cipher.doFinal(plaintextBytes);

这是要加密的图像文件

enter image description here

我收到了以下错误

发生了Java异常:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
    at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

请给我提示或程序,以便我能朝正确的方向前进。

由于

1 个答案:

答案 0 :(得分:4)

您需要使用AES来加密大数据。 RSA无法加密大于密钥大小的数据。 因此,您可以使用RSA加密AES密钥,使用AES(256位)加密整个图像(即为每个图像生成不同的AES密钥)。

如果你想将图像拆分成大量117字节的块并逐个加密,那么RSA也很慢,因此不适合加密大数据。


例如:

  public static byte[] encrypt(byte[] data) {
    try {
        KeyPair keyPair = initalizeKeyPair();

        final javax.crypto.Cipher rsa = javax.crypto.Cipher.getInstance("RSA");
        rsa.init(javax.crypto.Cipher.ENCRYPT_MODE, keyPair.getPublic());

        SecureRandom random = new SecureRandom();

        final byte[] secretKey = new byte[16];
        random.nextBytes(secretKey);

        final javax.crypto.Cipher aes = javax.crypto.Cipher.getInstance("AES");
        SecretKeySpec k = new SecretKeySpec(secretKey, "AES");
        aes.init(javax.crypto.Cipher.ENCRYPT_MODE, k);

        final byte[] ciphedKey = rsa.doFinal(secretKey);
        final byte[] ciphedData = aes.doFinal(data);

        byte[] result = new byte[256 + ciphedData.length];

        System.arraycopy(ciphedKey, 0, result, 0, 256);
        System.arraycopy(ciphedData, 0, result, 256, ciphedData.length);

        return result;
    } catch (... e) {
        throw new SomeException(e);
    }
}