Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7845219
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T17:09:23+00:00 2026-06-02T17:09:23+00:00

i am trying to encrypt and decrypt a string using RSA algorithm. Here the

  • 0

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];
    if(alg.equals("RSA"))
    {   

        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();


    if(alg.equals("RSA"))
    {   

        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");
    RSA.DECRYPT("RSA","[B@cb7e2c");
}

}

 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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T17:09:26+00:00Added an answer on June 2, 2026 at 5:09 pm

    [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("plainText:");
            System.out.println(new String(decryptWithPrivKey(cipherText,privKey),"UTF-8"));
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to encrypt/decrypt a string using 128 bit AES encryption (ECB). What I
Talking about javax.crypto.Cipher I was trying to encrypt data using Cipher.getInstance(RSA/None/NoPadding, BC) but I
I'm trying to encrypt and decrypt data using RSA in C#. I have the
I am trying to write encrypt/decrypt methods for AES 256 CBC encryption using PKCS5Padding
I am trying to encrypt strings in .NET by using a RSA algorithm and
I am trying to encrypt/decrypt a string using eith Rijndael or Aes and the
I'm trying to encrypt and decrypt files with C++, using this code: #include <iostream>
I am trying to encrypt/decrypt a string using c#. I've found countless tutorials on
I am trying to encrypt a string using C# and decrypt it using Python.
I am trying encrypt and decrypt one column in table. My code is like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.