Java RSA加密

前端之家收集整理的这篇文章主要介绍了Java RSA加密前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图来回编码一个简单的字符串“测试”.
public static String encode(Key publicKey,String data) throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException,IllegalBlockSizeException,BadPaddingException {

    byte[] byteData = data.getBytes(); // convert string to byte array

    Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object
    cipher.init(Cipher.ENCRYPT_MODE,publicKey); // initialize object's mode and key

    byte[] encryptedByteData = cipher.doFinal(byteData); // use object for encryption

    return new String(encryptedByteData); // convert encrypted byte array to string and return it

}

public static String decode(Key privateKey,BadPaddingException {

    byte[] byteData = data.getBytes(); // convert string to byte array

    Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object
    cipher.init(Cipher.DECRYPT_MODE,privateKey); // initialize object's mode and key

    System.out.println(byteData.length);

    byte[] decryptedByteData = cipher.doFinal(byteData); // use object for decryption

    return new String(decryptedByteData); // convert decrypted byte array to string and return it

}

然而,虽然加密工作正常(ALGORITHM是“RSA”),但是当尝试解密我刚从加密“测试”中获取的字符串时,我得到以下异常:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes

我应该分割256的块中的加密字节才能解密吗?

解决方法

您无法将随机字节可靠地转换为字符串.结果将取决于您运行此操作的机器上的默认字符编码.有很多编码,密文将被破坏,信息将丢失.

修改代码以使用byte []代替(doFinal())方法的结果.

如果需要将byte []转换为字符串,请使用Base-64等编码.

原文链接:https://www.f2er.com/java/127078.html

猜你在找的Java相关文章