Java RSA 加密

2024-06-19

我正在尝试来回编码一个简单的字符串“测试”。

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, 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.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

}

然而,虽然加密工作得很好(算法是“RSA”),但当尝试解密我刚刚从加密“test”获得的字符串时,我得到以下异常:

javax.crypto.IllegalBlockSizeException:数据不得超过 256 字节

我是否应该将加密字节分成 256 个字节以便能够解密?


您无法可靠地将随机字节转换为String。结果将取决于运行该程序的计算机上的默认字符编码。对于许多编码,密文将被损坏,信息将丢失。

修改您的代码以使用byte[]相反(“doFinal()”方法的结果。

如果您需要转换byte[]对于字符串,请使用 Base-64 等编码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java RSA 加密 的相关文章

随机推荐