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 7582861
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T18:32:25+00:00 2026-05-30T18:32:25+00:00

I have a very annoying problem with the unreliable encryption and decryption of string

  • 0

I have a very annoying problem with the unreliable encryption and decryption of string with the RSA algorithm in Java. It seams to only work about 35% of the times, and I can’t figure out why it sometimes does work and sometimes don’t. Here’s some test-code I wrote to try to verify the randomness in the encryption/decryption. It runs 100 laps and it encrypts and decrypts the same string every time and prints the number of times it was successful:

    public static void main(String[] args) throws Exception {
    byte[] dataToEncrypt = "Hello World!".getBytes("UTF-16LE");
    byte[] cipherData = null;
    byte[] decryptedData;

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512);
    KeyPair kp = kpg.genKeyPair();
    Key publicKey = kp.getPublic();
    Key privateKey = kp.getPrivate();
    KeyFactory fact = KeyFactory.getInstance("RSA");

    RSAPublicKeySpec pub = (RSAPublicKeySpec) fact.getKeySpec(publicKey,
            RSAPublicKeySpec.class);

    RSAPublicKeySpec spec = new RSAPublicKeySpec(pub.getModulus(), pub
            .getPublicExponent());
    KeyFactory factory = KeyFactory.getInstance("RSA");

    PublicKey publicKeyRSA = factory.generatePublic(spec);
    Cipher cipher = Cipher.getInstance("RSA");

    int k = 0;
    for (int i = 0; i < 100; i++) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, publicKeyRSA);
            cipherData = cipher.doFinal(dataToEncrypt);
        } catch (Exception e1) {
            System.out.println("Encrypt error");
        }

        String s = new String(cipherData, "UTF-16LE");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        try {
            decryptedData = cipher.doFinal(s.getBytes("UTF-16LE"));
            System.out.println("Decrypted: "
                    + new String(decryptedData, "UTF-16LE"));
            k += 1;
        } catch (Exception e1) {
            System.out.println("Decrypt error");
        }
    }
    System.out.println("Number of correct decryptions is: " + k);

}

I’ve tried to initialize the KeyPairGenerator with various values without any success.

Edit:
Now it works like a charm, thanks to Base64:

    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PublicKey;
    import java.security.spec.RSAPublicKeySpec;
    import javax.crypto.Cipher;

    public class Test {

    public static void main(String[] args) throws Exception {
    byte[] dataToEncrypt = "Hello World!".getBytes("UTF-16LE");
    byte[] cipherData = null;
    byte[] decryptedData;


    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512);
    KeyPair kp = kpg.genKeyPair();
    Key publicKey = kp.getPublic();
    Key privateKey = kp.getPrivate();
    KeyFactory fact = KeyFactory.getInstance("RSA");

    RSAPublicKeySpec pub = (RSAPublicKeySpec) fact.getKeySpec(publicKey,
            RSAPublicKeySpec.class);

    RSAPublicKeySpec spec = new RSAPublicKeySpec(pub.getModulus(), pub
            .getPublicExponent());
    KeyFactory factory = KeyFactory.getInstance("RSA");

    PublicKey publicKeyRSA = factory.generatePublic(spec);
    Cipher cipher = Cipher.getInstance("RSA");

    int k = 0;
    for (int i = 0; i < 100; i++) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, publicKeyRSA);
            cipherData = cipher.doFinal(dataToEncrypt);
        } catch (Exception e1) {
            System.out.println("Encrypt error");
        }

        String s = Base64.encodeBytes(cipherData);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        try {
            decryptedData = cipher.doFinal(Base64.decode(s));
            System.out.println("Decrypted: "
                    + new String(decryptedData, "UTF-16LE"));
            k += 1;
        } catch (Exception e1) {
            System.out.println("Decrypt error");
        }
    }
    System.out.println("Number of correct decryptions is: " + k);

}

}

  • 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-05-30T18:32:26+00:00Added an answer on May 30, 2026 at 6:32 pm

    This is the problem, or at least a problem:

    String s = new String(cipherData, "UTF-16LE");
    

    You’re taking arbitrary binary data and trying to create a string from it, treating it as if it’s UTF-16-encoded text. It’s not. It’s arbitrary binary data.

    Either keep it in binary form (as byte[]) or use base64 to convert it to text in a safe, reversible manner. (This public domain base64 encoder has a reasonable API, for example.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a very annoying problem on the application I've been contracted to work
I've recently started using GNU Screen but have run into a very annoying problem.
I have a layout that is working, but it has one very annoying problem..
I have a very annoying problem and I'm trying to find the simplest solution
I've got a very annoying problem with my Zend studio. I have a zend
We've got this very annoying problem with Scriptaculous and Internet Explorer 7/8. We have
I have a very annoying problem with jQuery and the datepicker from jQuery-UI. Here
I have a very annoying problem with LINQ and MS SQL Server. Im currently
Hey there, i got this very annoying problem: I have a CheckBoxList getting items
I have this very annoying problem I cannot figure out. This is the main

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.