Avinash Avinash - 1 year ago 108
Java Question

need Help in RSA ENCRYPTION(doFinal)

i am trying to encrypt and decrypt a string using RSA algorithm. Here the encryption is working good but problem is in decryption.
the code gets terminated when it reaches the doFinal in DECRYPT method.
Am i taking the input wrong or is there any problem with public and private keys?
please give me suggestions regarding this.
Thank u.

public class rsa
private KeyPair keypair;

public rsa() throws NoSuchAlgorithmException, NoSuchProviderException
KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keygenerator.initialize(1024, random);
keypair = keygenerator.generateKeyPair();
public String ENCRYPT(String Algorithm, String Data ) throws Exception
String alg = Algorithm;
String data=Data;
byte[] encrypted=new byte[2048];

PublicKey publicKey = keypair.getPublic();
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encrypted = cipher.doFinal(data.getBytes());
System.out.println("Encrypted String[RSA] -> " + encrypted);
return encrypted.toString();
public String DECRYPT(String Algorithm, String Data ) throws Exception
String alg = Algorithm;
byte[] Decrypted=Data.getBytes();


PrivateKey privateKey = keypair.getPrivate();
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dec = cipher.doFinal(Decrypted);

System.out.println("Decrypted String[RSA] -> " + dec.toString());

return Decrypted.toString();
public static void main(String[] args) throws Exception
rsa RSA=new rsa();
RSA.ENCRYPT("RSA", "avinash");


got exception as

Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
at EncryptionProvider.rsa.DECRYPT(rsa.java:56)
at EncryptionProvider.rsa.main(rsa.java:68)

Encrypted String[RSA] -> [B@4a96a

Answer Source

[B@cb7e2c is not the output of your encryption. It's the result of trying to print or call toString() on a byte[] object. (For example, look at the result of System.out.println(new byte[0]);)

Try feeding the encrypted byte[] directly back into the decryption function, and use new String(dec) to print the results. If you want to view/save the encrypted data as a string, encode it as hex or base64.

Here's the distinction. byte[] means an array of bytes. It is binary data, a series of 8 bit signed numbers. If you're used to working with ascii only, the distinction between a series of bytes and a String might seem trivial, but there are many ways to represent strings in binary. The encryption and decryption you're doing doesn't care what the string looks like or if the data represents a string at all; it's just looking at the bits.

If you want to encrypt a string, you'll need to convert it to a series of bytes. At the other end, once you've decrypted the bytes that make up a the string, you'll need to convert them back. myString.getBytes() and new String(myBytea) are often effective, but a bit sloppy since they just use default encoding. If Alice's system used utf-8 and Bob's used utf-16, her message wouldn't make much sense to him. So it's always best to specify the character encoding using, for instance, myString.getBytes("utf-8") and new String(myBytea,"utf-8").

Here are a few functions from a project I'm working on, along with a demonstration main function:

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.xml.bind.DatatypeConverter;

public class RSAExample {
    private static byte[] h2b(String hex){
        return DatatypeConverter.parseHexBinary(hex);
    private static String b2h(byte[] bytes){
        return DatatypeConverter.printHexBinary(bytes);

    private static SecureRandom sr = new SecureRandom();

    public static KeyPair newKeyPair(int rsabits) throws NoSuchAlgorithmException {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(rsabits, sr);
        return generator.generateKeyPair();

    public static byte[] pubKeyToBytes(PublicKey key){
        return key.getEncoded(); // X509 for a public key
    public static byte[] privKeyToBytes(PrivateKey key){
        return key.getEncoded(); // PKCS8 for a private key

    public static PublicKey bytesToPubKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException{
        return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));
    public static PrivateKey bytesToPrivKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException{
        return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(bytes));

    public static byte[] encryptWithPubKey(byte[] input, PublicKey key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(input);
    public static byte[] decryptWithPrivKey(byte[] input, PrivateKey key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(input);

    public static void main(String[] args) throws Exception {
        KeyPair kp = newKeyPair(1<<11); // 2048 bit RSA; might take a second to generate keys
        PublicKey pubKey = kp.getPublic();
        PrivateKey privKey = kp.getPrivate();
        String plainText = "Dear Bob,\nWish you were here.\n\t--Alice";
        byte[] cipherText = encryptWithPubKey(plainText.getBytes("UTF-8"),pubKey);
        System.out.println("cipherText: "+b2h(cipherText));
        System.out.println(new String(decryptWithPrivKey(cipherText,privKey),"UTF-8"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download