Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Encrypting a zero-length byte array

843811Feb 24 2010 — edited Feb 24 2010
The following code works when the String value to encrypt/decrypt is non-zero length, but fails when it is an empty string. Is this expected?
//String cleartext = "mytext"; // This works
String cleartext = "";  // This fails

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom());
KeyPair kp = keyPairGen.generateKeyPair();

byte[] clearBytes = cleartext.getBytes("UTF8");
byte[] cryptBytes = null;

Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
System.out.println("Using provider: "  +c.getProvider().getName());+

+c.init(Cipher.ENCRYPT_MODE, kp.getPublic());+
+cryptBytes = c.doFinal(clearBytes);+

+// Reverse the encryption+
+c.init(Cipher.DECRYPT_MODE, kp.getPrivate());+
+clearBytes = c.doFinal(cryptBytes);+

+String newClearText = new String(clearBytes, "UTF8");+
+System.out.println("Encrypt/decrypt complete, cleartext is \""+newClearText+"\"");
Results are:

Using provider: IBMJCE
javax.crypto.BadPaddingException: Not PKCS#1 block type 2 or Zero padding
at com.ibm.crypto.provider.RSASSL.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(Unknown Source)
...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 24 2010
Added on Feb 24 2010
1 comment
445 views