我试图来回编码一个简单的字符串“测试”.
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的块中的加密字节才能解密吗?