10/12/2004

Using RSA encryption with Java

Filed under: — Aviran Mordo @ 10:53 am

Now that we have the two keys we can encrypt and decrypt information. In order to do that we are going to use javax.crypto.Cipher. This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.

In order to create a Cipher object, the application calls the Cipher’s getInstance method, and passes the name of the requested transformation to it. Optionally, the name of a provider may be specified.
A transformation is a string that describes the operation (or set of operations) to be performed on the given input, to produce some output. A transformation always includes the name of a cryptographic algorithm, and may be followed by a feedback mode and padding scheme. A transformation is of the form:”algorithm/mode/padding” or “algorithm”
In our example we’ll encrypt a message using our public key.


/**
* Encrypt a text using public key.
* @param text The original unencrypted text
* @param key The public key
* @return Encrypted text
* @throws java.lang.Exception
*/
public static byte[] encrypt(byte[] text, PublicKey key) throws Exception
{

    byte[] cipherText = null;
    // get an RSA cipher object and print the provider
    Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);

    System.out.println(”nProvider is: ” + cipher.getProvider().getInfo());

    // encrypt the plaintext using the public key
    cipher.init(Cipher.ENCRYPT_MODE, key);
    cipherText = cipher.doFinal(text);
    return cipherText;

}

The opposite method is to decrypt a message that was encrypted using a public key. Remember the only one who can decrypt an encrypted message is the one with the private key.


/**
* Decrypt text using private key
* @param text The encrypted text
* @param key The private key
* @return The unencrypted text
* @throws java.lang.Exception
*/
public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
{

    byte[] dectyptedText = null;
    // decrypt the text using the private key
    Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);
    cipher.init(Cipher.DECRYPT_MODE, key);
    dectyptedText = cipher.doFinal(text);
    return dectyptedText;

}

 

Pages: 1 2 3

104 Responses to “Using RSA encryption with Java”

  1. Daniel S.G. Says:

    Thanks a lot!
    It was very usefull for me. I had a problem encryting long bytes arrays, this article solved my problens; which were that I didn’t have a copyBytes() method to pass full byte arrays. How ever I tryed to encript a byte array which was not full complete and then , when I tryed to decript it I had exceptions with block size padding and similar.

    Regards from Spain.
    Danisg

    (Excuse my bad English)

  2. Bilal Says:

    hello i am trying to use RSA in java
    i this is the code i have written:

    import java.io.*;
    import java.security.*;
    import javax.crypto.*;

    class enc {

    public static void main (String[] args) throws NoSuchAlgorithmException,

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

    BadPaddingException, NoSuchPaddingException {

    /* Generate a RSA key pair */

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”RSA”);
    SecureRandom random = SecureRandom.getInstance(”SHA1PRNG”, “SUN”);

    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();
    //System.out.println(”Public is” + pub);
    //System.out.println(”Private is” + priv);

    /* Create the cipher */
    Cipher rsaCipher = Cipher.getInstance(”RSA”);

    // Initialize the cipher for encryption
    rsaCipher.init(Cipher.ENCRYPT_MODE, pub);

    // Cleartext
    byte[] cleartext = null;
    cleartext = “This is Bilal”.getBytes();
    //byte[] cleartext = “This is Bilal”.getBytes();
    //String cleartext = “This is just an example”;
    System.out.println(”the original cleartext is: ” + cleartext.toString());
    //System.out.println(”the original cleartext is: ” + cleartext);

    // Encrypt the cleartext
    byte[] ciphertext = null;
    ciphertext = rsaCipher.doFinal(cleartext);
    //byte[] ciphertext = rsaCipher.doFinal(cleartext);
    //String ciphertext = rsaCipher.doFinal(cleartext);
    System.out.println(”the encrypted text is: ” + ciphertext.toString());

    // Initialize the same cipher for decryption
    rsaCipher.init(Cipher.DECRYPT_MODE, priv);

    // Decrypt the ciphertext
    byte[] cleartext1 = rsaCipher.doFinal(ciphertext);
    //String cleartext1 = rsaCipher.doFinal(ciphertext);
    System.out.println(”the final cleartext is: ” + cleartext1.toString());
    //System.out.println(”the final cleartext is: ” + cleartext1);
    }
    }

    when i am getting the output of plain and encrypted text, it is totally different

    this is the output i have:

    the original cleartext is: [B@18eb9e6
    the encrypted text is: [B@1ca318a
    the final cleartext is: [B@17a8913

    would u help ma plz
    thanks

  3. Aviran Says:

    You need to replace the line
    Cipher rsaCipher = Cipher.getInstance("RSA");
    with
    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

  4. Sarah Says:

    But, I also face this problem…
    I cannot decrypt file to original file…..I get the original file then output encrypted file….then i get encrypted file to do decryption..
    the output decrypted file is all unread characters….
    Anybody can solve my problem?? Thankyou very much!!

  5. Daryl Says:

    Your problem isn’t the cryptography part of your code, it’s your implentation for printing the byte data on screen. Using the toString() for a byte array will print the memory address of the array not the contents. If you want to see the contents of the byte array you have to use a loop and iterate through the elements and print them individually. I checked your code and it works perfectly.

  6. Dhanya Says:

    But I also face this problem.
    I want the contents of the byte array to be displayed for the above code.
    Anybody can solve my problem??
    Thank you very much in advance!!

  7. Aviran Mordo Says:

    Dhanya, The answer is in the forum.

    Click here

  8. Dhanya Says:

    It works.
    Thanks for giving me a reply,

  9. mahesh Says:

    Can U please help me

    I need the code for encryption and decryption in java using the RSA algorithm.

  10. Aviran Mordo Says:

    At the end of the article (page 3) you have a link to download the code

  11. radhakrishnan Says:

    i need encryption and decryption algorithm in java

  12. olumide olubuse Says:

    pls ma i’m writing my B.tech thesis in java titled security of data in electronic learning system using data encryption and biometrics. i have design the e-learning portal using servlet ( though i’m new to java environment) ; i am finding problem in the secuity of the data involved especially data encryption (RSA) and facial recognition; pls can i have some snippet of code for any of this algorithm or both.
    thanks ma,

    from
    ladoke akintola university of technology
    ogbomoso,oyo state
    nigeria

  13. Thanks Says:

    Thanks very much for the code.

  14. chakchai so-in Says:

    how to encrypt the message which is longer than 128 bytes with RSA?

  15. Aviran Mordo Says:

    Check out the file encryption for example, basically you do it in blocks

  16. Anonymous Says:

    A very good Java RSA example

  17. Sada Says:

    A very good Java RSA example

  18. Sivababu Says:

    Hi ,
    This code is really help me lot. i have one more doubt.
    How do i generated public key and private key to store it in different files.

  19. mzhou Says:

    This is a very nice example.
    I have one problem using the keys generated using the example code:
    The keys works fine for encryption, decryption, but I cannot use it for digital signature, when I do:
    Signature dsig = Signature.getInstance(priKey.getAlgorithm());

    I got the following exception:

    java.security.NoSuchAlgorithmException: RSA Signature not available
    at java.security.Security.getEngineClassName(Unknown Source)
    at java.security.Security.getEngineClassName(Unknown Source)
    at java.security.Security.getImpl(Unknown Source)
    at java.security.Signature.getInstance(Unknown Source)

    Did I miss anything? Thanks.

  20. mad Says:

    doubt, methods getPublicKeyFromString and getPrivateKeyFromString have problems:

    Caused by: java.security.spec.InvalidKeySpecException: Unknown key spec: Could not decode public key from BER.

    Can U please help me?

  21. demirel Says:

    Hello,

    In order to run this example, “iaik_jce.jar” is needed.
    How can I find this jar file?

  22. elpiloto Says:

    try this:

    new String(plaintext, “8859_1″);

    //where byte[] cleartext = null;

  23. Baiju from kerala,India Says:

    this 4 u da(mzhou)
    KeyPairGenerator keygen=KeyPairGenerator.getInstance(”DSA”);
    KeyPair pair=keygen.generateKeyPair();
    Signature sig=Signature.getInstance(”SHA/DSA”);
    PrivateKey priv=pair.getPrivate();
    PublicKey pub=pair.getPublic();

    first u can use this code,

    the remaining part of the code can be get from java 2 API Specification for cryptography

    Thanks daaaaaaaaaaaa

  24. Vijay M Says:

    Are there any copyright restrictions for me to use your RSAEncryptUtil class in my system?

  25. Aviran Mordo Says:

    Vijay: You are free to use this code without any restrictions.

  26. andika Says:

    thanks for the artikel,
    i would like to generate keypair on desktop and transfer the private key to smartcard while i keep the public key on desktop.
    Then i ‘m encrypt some data on desktop using the public key and transfer the enrypted data to smartcard. On smartcard , javacard has provide the cryptography library for decrypting the encrypted data using it’s private key .
    Could it be done, coz i’m using different platform on desktop and smartcard?.
    On desktop i;m using boucycastle jce provider to generate the key pair and using the public the encrypt data, then on the smartcard i’m using javacard library that provide by sun to decrypt the data using private key the generated from desktop.

    sorry for my english, i hope u understand what i wrote…

  27. Aviran Mordo Says:

    I don’t know if this will work, but in theory it should work as long as you use the same algorithm. The only way to know for sure is to try.

  28. andika Says:

    thanks for the code,
    i have read the source from bouncy castle and i know KeyPairGenerator for rsa instance generate JCERSAPublicKey and JCERSAPrivateCrtKey .

    how if i just need the pair JCERSAPublicKey and JCERSAPrivateKey to generate, is it possible?

  29. vinodh Says:

    Its a very good article to know about RSA..i am doing a project in RSA to encrypt a MPEG file and decrypt the same..i had a got an idea implement in text file.how can i do it in Mpeg Files..if so can u help me in getting the source codes…Thanks a lot..

  30. vinodh Says:

    Thanks a lot this was a very usefull article to know about RSA.. i am doing a project in rsa to encrypt the MPEG file and transfer it to the other system using Socket concept..on receiving the encrypted file i have to Decrypt it to get the original MPEG file..can u help me with the source codes for the above to encrypt-decrypt MPEG file using RSA..Thanks for ur Help…

  31. jana Says:

    hello
    Plz help me out in encryption and decryption in RSA using JAVA.I need the coding for the server client program.Im doing my project in this.Please help thro’ this!

    by jana

  32. arun prakash Says:

    could you help me with a code that alowws me to break a 12*24 matrix into 2*4 modules all of the same size.

  33. rizwan Says:

    when i compile this code no errors occurs but while running the code following errors occurs
    java.security.NoSuchAlgorithmException: RSA Signature not available
    at java.security.Security.getEngineClassName(Unknown Source)
    at java.security.Security.getEngineClassName(Unknown Source)
    at java.security.Security.getImpl(Unknown Source)
    at java.security.Signature.getInstance(Unknown Source)

  34. Joen S Says:

    “Standard Java 2 distribution includes security provider support for generation of RSA digital signatures, but does NOT contain a provider implementation for generating RSA encrypted data. An extra provider must be added to obtain this capability from standard Java 2, such as the Bouncy Castle Provider.”

  35. Ronnit Says:

    How will i run this code please reply??

  36. ronnit Says:

    From where will i get all the packages and how will i run this code plz explain in detail like from cmd javac etc…

  37. Aviran Mordo Says:

    You can find the BouncyCastle link on the first page and the packaged java files on the last page of this article.

    This code is not an application that you can run, you need to write your own application and use this code as a library to handle encryption.

  38. Anonymous Says:

    I am writing up my own program which does the same thing as yours, except it can store the keys in a file. I can store the keys easily, but I cannot retrieve them because each key need be initialized with a special constructor, and so a key object seems unable to take any arguments. Is there a way to get around this?

  39. jai shukla Says:

    Hi I am getting some problem in the above code.
    1. When i use
    Cipher rsaCipher = Cipher.getInstance(”RSA/NONE/NoPadding”);
    Then i get a error
    java.security.NoSuchAlgorithmException: Cannot find any provider supporting RSA/NONE/NoPadding
    at javax.crypto.Cipher.getInstance(DashoA6275)
    at RSAEnc.main(RSAEnc.java:30)

    2. When i give the provider mean
    Cipher rsaCipher = Cipher.getInstance(”RSA/NONE/NoPadding”,”SunRsaSign”);

    Then i get following error
    java.security.NoSuchAlgorithmException: No such algorithm: RSA
    at javax.crypto.SunJCE_b.c(DashoA6275)
    at javax.crypto.SunJCE_b.a(DashoA6275)
    at javax.crypto.Cipher.a(DashoA6275)
    at javax.crypto.Cipher.getInstance(DashoA6275)
    at RSAEnc.main(RSAEnc.java:30)
    3. When i use above code mean
    Cipher.getInstance(”RSA”);
    Then i get following error

    java.security.NoSuchAlgorithmException: Cannot find any provider supporting RSA
    at javax.crypto.Cipher.getInstance(DashoA6275)
    at RSAEnc.main(RSAEnc.java:30)

    Please help me asap.
    Thanks in advance

  40. gaurav Says:

    u have been a great help

    thanks
    gaurav

  41. K.Sankar Says:

    for Encrypt the data

    I gives

    Cipher rsaCipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);

    but it returns the exception called

    Exception in thread main java.security.NoSuchAlgorithmException:
    Cannot find any Provider supporting RSA/ECB/PKCS1Padding

    at javax.crypto.Cipher.getInstance(DashoA6275)

    at enc.main(enc.java:30)

    please help me

  42. Aviran Mordo Says:

    You need to add a provider (bouncyCastle)
    Security.addProvider(new BouncyCastleProvider());

  43. assom issa Says:

    I have a project in data security & i have to write a java code to implement the RSA algorithm Encryption & Decryption for TWO letters at a time! & the generation of the key but i can’t figure it out! CAN YOU HELP ME WITH MY PROBLEM!

  44. mustafa Says:

    Implement each of the following
    1-Miler-Rabin Algorithm (chap 8)
    2-The extended Euclid’s algorithm (chap 8)
    KD Ξ ke-1 mod ø(n)
    3-The RSA algorithm (to encrypt/decrypt 2 letters at a time).
    please send me the solution at my e-mail : mst_jazz@yahoo.com

  45. vijaya Says:

    hi,
    the code is damn good, but however the packages that are used are really no known to me even though i’m in the end of Advanced Java.Actually i need to do a project i.e Secured File Transfer System using RSA algorithm in JAVA so need some help. could u please help me out, the algorithm is really very confusing to me becaz i’m basically from an electrical background, so plzzzzzzzzzzzzzzz kindly helpme out to complete my project.

  46. vijaya Says:

    plzzzzzz helpme out as soon as possible. u can help me out at vijju_31@rediffmail.com. it is really verrrrrrry urgent for me.

  47. Ivo Says:

    Thks man!!! very usefull!!!

  48. Helen Says:

    Good explanation and great example. Thank you very much!

  49. madhuri Says:

    i have to encrypt and decrypt the folder using DES algoritm, please help me

  50. Surya Says:

    I am getting this error while trying to get a PublicKey from String .. Please help…

    java.security.spec.InvalidKeySpecException: Unknown key spec: Could not decode public key from BER.
    at com.sun.net.ssl.internal.ssl.JS_KeyFactory.engineGeneratePublic(DashoA6275)
    at java.security.KeyFactory.generatePublic(KeyFactory.java:221)
    at aspone.module.view.util.RSAEncryptUtil.getPublicKeyFromString(RSAEncryptUtil.java:205)

    Please mail me at suryakiranl@infotechsw.com

  51. muthukumar Says:

    hi all,

    i have been trying the following program. when i compile this code no errors wil occur. but while i trying to execute this code, it shows

    ” NoSuchAlgorithmException: cannot find any Provider Supporting RSA/ECB/PKCS1Padding

    at javax.crypto.Cipher.getInstance(DashoA6275)

    the code wil follw.

    import java.io.*;
    import java.security.*;
    //import java.security.Provider;
    //import java.security.BouncyCastleProvider;
    import javax.crypto.*;

    class enc {

    public static void main (String[] args) throws NoSuchAlgorithmException,

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

    BadPaddingException, NoSuchPaddingException
    {
    //BouncyCastleProvider bcp=new BouncyCastleProvider();
    //Security.addProvider(new BouncyCastleProvider());
    //Security.addProvider(bcp);

    /* Generate a RSA key pair */

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”RSA”);
    SecureRandom random = SecureRandom.getInstance(”SHA1PRNG”, “SUN”);

    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    /* Create the cipher */
    Cipher rsaCipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);

    // Initialize the cipher for encryption
    rsaCipher.init(Cipher.ENCRYPT_MODE, pub);

    // Cleartext
    byte[] cleartext = null;
    cleartext = “This is Bilal”.getBytes();
    //byte[] cleartext = “This is Bilal”.getBytes();
    //String cleartext = “This is just an example”;
    System.out.println(”the original cleartext is: ” + cleartext.toString());
    //System.out.println(”the original cleartext is: ” + cleartext);

    // Encrypt the cleartext
    byte[] ciphertext = null;
    ciphertext = rsaCipher.doFinal(cleartext);
    //byte[] ciphertext = rsaCipher.doFinal(cleartext);
    //String ciphertext = rsaCipher.doFinal(cleartext);
    System.out.println(”the encrypted text is: ” + ciphertext.toString());

    // Initialize the same cipher for decryption
    rsaCipher.init(Cipher.DECRYPT_MODE, priv);

    // Decrypt the ciphertext
    byte[] cleartext1 = rsaCipher.doFinal(ciphertext);
    //String cleartext1 = rsaCipher.doFinal(ciphertext);
    System.out.println(”the final cleartext is: ” + cleartext1.toString());
    //System.out.println(”the final cleartext is: ” + cleartext1);
    }
    }

  52. Anonymous Says:

    You need to add a provider. Java does not provide RSA Algorithm, this is why you need the BouncyCastle

  53. muthukumar Says:

    thanks anonymous…

    But i did program using BouncyCastle. it show some errors.

    ” cannot resolve symbol : BoucyCastleProvider”.

    even though BouncyCastleProvider is already existed in my system.

    and if i used this BouncyCastleProvider, it shows error while i am compiling this program

    what should i do?

    regards,
    Muthukumar

  54. Aviran Mordo Says:

    Make sure you have the bouncy castle jar file in your class path

  55. mos Says:

    When I encrypt a String “bubba” it decrypts to “bubb”, I have followed the guide very carefully, any hints?

  56. surya Says:

    this artile is very helpfull to me
    but i have some doubts like
    can we encrypt with either publik or private key and decrypt with the other
    and can we do encryption on a file more than one time with different keys

    please help me
    thanks in advance

  57. Aviran Mordo Says:

    The answer to both questions is yes, although I’m not 100% sure about switching the private and public keys roles

  58. Amir Says:

    Hey guys,

    Thanks for code…

    I want to encrypt my data by the key in /etc/ssh/ssh_host_key.pub and decrypt it by the key provided in /etc/ssh/ssh_host_key

    but they are String … how can I cast it into Publickey and Privatekey object type. and how about the format… are they in X509 certificate format??

    anyone has any idea?

    Thanks in advance for your reply!!

    Amir.

  59. Amir Says:

    Sorry the files are ssh_host_rsa_key and ssh_host_rsa_key.pub !!!

  60. Amir Says:

    Following to my question, I used your code and use the function so called ” getPublicKeyFromString”. the problem is the program is stucked on the line

    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    and after that it is exiting with no error!!!! I have no idea … have you chaeked that before? and DO you have any idea??

    Thanks,

    Amir.

  61. Phil Quinlan Says:

    I hope you can help me with a problem. I am using the Public Key to encrypt a unique ID Number. I then store the public key as a string. When i encrypt the same text with the same public key, i get different results, therefore it is impossible for me to use the ID Number as once its encrypted i cant find it without de-crypting. I am doing something wrong? Should it create the same encrypted string from the same public key?

    Hope this makes sense.

  62. jay Says:

    Hi,
    I am trying to run this code in eclipse but i am getting errors :
    java.lang.Error: Unresolved compilation problems:
    The import javax.crypto cannot be resolved
    Cipher cannot be resolved or is not a type
    Can u please tell me why i am getting these kind of errors?
    Thanks

  63. Aviran Mordo Says:

    I can only guess that you are missing the Bouncy Castle jar file from your classpath

  64. jay Says:

    where can i get Bouncy castle jar file?

  65. Aviran Mordo Says:

    There is a link in the first page of the article, but here it is again http://www.bouncycastle.org/latest_releases.html

  66. jay Says:

    Hi,

    Now i have added external jars but now i am getting errors:
    java.lang.UnsupportedClassVersionError: keyserver/KeyRegistry (Unsupported major.minor version 49.0)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Exception in thread “main”
    Thanks

  67. Aviran Mordo Says:

    This is hard to guess, but I think that some of your jar files do not match the JVM version you are using

  68. jay Says:

    Hi,
    there was problem with java version, i fixed that problem. But now i am getting errors:
    Exception in thread “main” java.security.InvalidKeyException: No installed provider supports this key: (null)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at security.RSAEncryptUtil.encrypt(RSAEncryptUtil.java:65)
    at security.RSAEncryptUtil.encrypt(RSAEncryptUtil.java:88)
    at bankclient.ClientTrial2.main(ClientTrial2.java:49)

    Do i need to install this provider?
    Thanks

  69. Aviran Mordo Says:

    Did you read the article ? Look at the init method above

  70. Anonymous Says:

    hi

    Do u know how to convert (RSA)publickey to byte array and viceversa?
    Thanks

  71. inflatable Says:

    Good post,thank you for your great words!

  72. Subhrajyoti Choudhury Says:

    Hi ,
    I looked at your article and looks like I just what I need :
    I am looking for RSA implemetation using Java . Can any one help me in finding one that I should be able to use out of the box .?Apart from that I also want to just port the encryption logic from java to java script. So if I get the same solution in java script than nothing like it .

  73. Aviran Mordo Says:

    As for the out of the box library you can use the Bouncy Castle Provider as noted in the article. I don’t know of any javascript implementations (I never needed one)

  74. Rami Says:

    I am using the RSA to encrypt a string. When i encrypt the same text with the same public key, i get different results each time, thus, there is no way to compare encrypted text unless they are decrypted back. Anyone has idea what to do to solve this issue!!!

    Thanks

  75. milan Says:

    Hi, the code works fine when I compile it, but when I run it the following errors come up:

    After using “RSAEncryptUtil.init();”, I get:

    Exception in thread “main” java.lang.UnsupportedClassVersionError: Bad version number in .class file
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at src.rsa.main(rsa.java:8)

    Does this mean the BouncyCastle package I have is too old, and uses a different jdk version?

    Thanks,
    Milan

  76. milan Says:

    I fixed the above version problem, but now i get this error when running:

    Exception in thread “main” javax.crypto.BadPaddingException: Data must start with zero
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:308)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:255)
    at com.sun.crypto.provider.RSACipher.a(DashoA12275)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA12275)
    at javax.crypto.Cipher.doFinal(DashoA12275)
    at src.RSAEncryptUtil.decrypt(RSAEncryptUtil.java:110)
    at src.RSAEncryptUtil.decrypt(RSAEncryptUtil.java:133)
    at src.rsa.main(rsa.java:15)

    could you help me? thanks

  77. Jag Says:

    Confused

  78. Calin Says:

    Please post the corect code!!! I`m so confused…… :(

  79. target Says:

    Hi i am doing a program for digital signature, through implementing RSA as a basis for the algorithm. I want to know how to hav a fixed private key and a public key for the program rather than genorating a new one everytime..

  80. Aviran Mordo Says:

    Just store the key in a database or file, and use it next time

  81. OneUser Says:

    I have singed a public key using Signature class like the following

    Signature sig = Signature.getInstance(”SHA1withRSA”);
    sig.initSign(priKey);
    sig.update(msg.getBytes());
    byte[] b = sig.sign();

    then in another application I need to get the hash value included in the signature i.e. in b; to compare it with the hash value of the original message before the signature. But when I decrypt the signature using the public key to get the hash value and compare it with the original hash value THEY ARE NOT THE SAME!!
    I would appriciate it if anyone could point out the problem…

    Thanks in advance

  82. KeyJen Says:

    KeyJen is a Java application that will generate an RSA type 1 keypair. I have used these keys with openSSH daemon and Rsync. Source code and GPL. Released for educational purposes

    See

    http://www.cheersdata.com

  83. Rick Says:

    Excellent! Thank you.

  84. chindhu Says:

    import java.io.*;
    import java.security.*;
    //import java.security.Provider;
    //import java.security.BouncyCastleProvider;
    import javax.crypto.*;

    class enc {

    public static void main (String[] args) throws NoSuchAlgorithmException,

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

    BadPaddingException, NoSuchPaddingException
    {
    //BouncyCastleProvider bcp=new BouncyCastleProvider();
    //Security.addProvider(new BouncyCastleProvider());
    //Security.addProvider(bcp);

    /* Generate a RSA key pair */

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”RSA”);
    SecureRandom random = SecureRandom.getInstance(”SHA1PRNG”, “SUN”);

    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    /* Create the cipher */
    Cipher rsaCipher = Cipher.getInstance(”RSA”);

    // Initialize the cipher for encryption
    rsaCipher.init(Cipher.ENCRYPT_MODE, pub);

    // Cleartext
    byte[] cleartext = null;
    cleartext = “hi “.getBytes();
    System.out.println(cleartext.toString()); // This will print the Object’s reference address
    String theString = new String(cleartext);
    System.out.println(theString); // This will print

    //System.out.println(”the original cleartext is: ” + cleartext);

    // Encrypt the cleartext
    byte[] ciphertext = null;
    ciphertext = rsaCipher.doFinal(cleartext);
    //byte[] ciphertext = rsaCipher.doFinal(cleartext);
    //String ciphertext = rsaCipher.doFinal(cleartext);
    System.out.println(”the encrypted text is: ” + ciphertext.toString());

    // Initialize the same cipher for decryption
    rsaCipher.init(Cipher.DECRYPT_MODE, priv);

    // Decrypt the ciphertext
    byte[] cleartext1 = rsaCipher.doFinal(ciphertext);
    //String cleartext1 = rsaCipher.doFinal(ciphertext);
    System.out.println(”the final cleartext is: ” + cleartext1.toString());
    //System.out.println(”the final cleartext is: ” + cleartext1);
    }
    }

    heh wenever i try bove pgm d output s lik

    hi
    the encrypted text is: [B@1b10d42
    the final cleartext is: [B@1f7d134

    wat ever d given text s d ecrypted output is displaying same and the decryption is also not workin out.pls help me:(

  85. chindhu Says:

    Wenever i try d following Pgm watever d inPut is im getting the same encryPted outPut as
    [B@1f20eeb
    hi
    the encrypted text is: [B@1b10d42
    the final cleartext is: [B@1f7d134

    and the decryPtion is also not working.. Pls helP me out:(

    import java.io.*;
    import java.security.*;
    //import java.security.Provider;
    //import java.security.BouncyCastleProvider;
    import javax.crypto.*;

    class enc {

    public static void main (String[] args) throws NoSuchAlgorithmException,

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

    BadPaddingException, NoSuchPaddingException
    {
    //BouncyCastleProvider bcp=new BouncyCastleProvider();
    //Security.addProvider(new BouncyCastleProvider());
    //Security.addProvider(bcp);

    /* Generate a RSA key pair */

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”RSA”);
    SecureRandom random = SecureRandom.getInstance(”SHA1PRNG”, “SUN”);

    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    /* Create the cipher */
    Cipher rsaCipher = Cipher.getInstance(”RSA”);

    // Initialize the cipher for encryption
    rsaCipher.init(Cipher.ENCRYPT_MODE, pub);

    // Cleartext
    byte[] cleartext = null;
    cleartext = “hi “.getBytes();
    System.out.println(cleartext.toString()); // This will print the Object’s reference address
    String theString = new String(cleartext);
    System.out.println(theString); // This will print

    //System.out.println(”the original cleartext is: ” + cleartext);

    // Encrypt the cleartext
    byte[] ciphertext = null;
    ciphertext = rsaCipher.doFinal(cleartext);
    //byte[] ciphertext = rsaCipher.doFinal(cleartext);
    //String ciphertext = rsaCipher.doFinal(cleartext);
    System.out.println(”the encrypted text is: ” + ciphertext.toString());

    // Initialize the same cipher for decryption
    rsaCipher.init(Cipher.DECRYPT_MODE, priv);

    // Decrypt the ciphertext
    byte[] cleartext1 = rsaCipher.doFinal(ciphertext);
    //String cleartext1 = rsaCipher.doFinal(ciphertext);
    System.out.println(”the final cleartext is: ” + cleartext1.toString());
    //System.out.println(”the final cleartext is: ” + cleartext1);
    }
    }

  86. Aviran Mordo Says:

    You can NOT do cleartext1.toString() - this is a byte array, you’ll need to convert the byte[] to String. Example: String theText = new String(cleartext1);

  87. chindhu Says:

    heh tanx a lot..
    i got d output:)

  88. sharad kumar Says:

    Hi All,

    This is a great article. Was very helpful to get the basics clear. But some help is definitely required to become a pro I guess :)

    This is the error I get when I try to use the above program,with very minor changes. It seems the error happens while decrypting and encryption is happening.
    Error Text starts
    ——————
    Provider is: BouncyCastle Security Provider v1.39
    encrypted text:[B@1551f60
    Start decryption
    error:javax.crypto.BadPaddingException: unknown block type
    Exception in thread “main” java.lang.Exception: no such algo exists:javax.crypto.BadPaddingException: unknown block type
    at RSA.main(RSA.java:92)
    —————
    Error Text ends

    Sample Code starts
    ———————–
    import java.io.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;

    import org.bouncycastle.jce.provider.*;
    import sun.misc.*;

    public class RSA {

    protected static final String ALGORITHM = “RSA”;
    public static void init()
    {
    //Security.addProvider(new BouncyCastleProvider());
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    public static KeyPair generateKey() throws NoSuchAlgorithmException
    {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
    keyGen.initialize(1024);
    KeyPair key = keyGen.generateKeyPair();
    return key;
    }

    public static byte[] encrypt(byte[] cipherText, PublicKey key) throws Exception
    {
    //byte[] cipherText = encrypt(strNumber.getBytes(”UTF8″),key);
    byte[] encryptedText = null;
    try
    {
    Cipher cipher = Cipher.getInstance(”RSA/None/PKCS1Padding”);
    System.out.println(”\nProvider is: ” + cipher.getProvider().getInfo());

    // encrypt the plaintext using the public key
    cipher.init(Cipher.ENCRYPT_MODE, key);
    encryptedText = cipher.doFinal(cipherText);
    }
    catch (Exception e)
    {
    System.out.println(”error:”+ e);
    throw e;
    }
    return cipherText;
    }

    public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
    {
    byte[] dectyptedText = null;
    try
    {
    // decrypt the text using the private key
    Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);

    System.out.println(”Start decryption”);
    cipher.init(Cipher.DECRYPT_MODE, key);
    dectyptedText = cipher.doFinal(text);
    }
    catch (Exception e)
    {
    System.out.println(”error:”+e);
    throw e;
    }
    return dectyptedText;

    }

    public static void main (String args[])
    throws UnsupportedEncodingException, Exception, NoSuchAlgorithmException
    {
    String strNumber = “5641820300097008″;

    init();
    try {
    KeyPair key = generateKey();
    PublicKey pubKey = key.getPublic();
    byte[] cipherText = encrypt(strNumber.getBytes(”UTF8″), pubKey);
    System.out.println(”encrypted text:”+cipherText);

    PrivateKey privKey = key.getPrivate();
    byte[] decryptedText = decrypt(cipherText, privKey);
    String originalText = new String(decryptedText);
    System.out.println(”original text:”+originalText);

    } catch (NoSuchAlgorithmException e) {
    throw new NoSuchAlgorithmException(”no such algo exists:”+e);
    }
    catch (UnsupportedEncodingException e) {
    throw new UnsupportedEncodingException(”no such algo exists:”+e);
    }
    catch (Exception e) {
    throw new Exception(”no such algo exists:”+e);
    }
    }

    }
    ———————–
    Sample Code ends

    Any help will be highly appreciated.
    Kind Regards,
    sharad

  89. Anonymous Says:

    Change:
    Cipher cipher = Cipher.getInstance(”RSA/None/PKCS1Padding”);
    To
    Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);

  90. sharad kumar Says:

    Hi Anonymous,

    sorry to say but before posting this message I was modifying this code and this went as it is here. I realized this mistake but I didn’t know how to modify my post !
    The cipher object should be using same parameters in getInstance while encrypting/decrypting and I have done it but it still gives the same error.

    Any other clue ?
    regards,
    sharad

  91. sri krishna Says:

    hey guys i code the correct working code for rsa using java

    import java.io.*;
    import java.security.*;
    import javax.crypto.*;

    class rsa{

    public static void main (String[] args) throws NoSuchAlgorithmException,

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

    BadPaddingException, NoSuchPaddingException {

    /* Generate a RSA key pair */
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”RSA”);
    SecureRandom random = SecureRandom.getInstance(”SHA1PRNG”, “SUN”);
    keyGen.initialize(1024, random);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    /* Create the cipher */
    Cipher rsaCipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);

    // Initialize the cipher for encryption
    rsaCipher.init(Cipher.ENCRYPT_MODE, pub);

    // Cleartext
    String plaintext;
    plaintext= “This is Bilal”;
    byte[] cleartext = plaintext.getBytes();
    System.out.println(”the original cleartext is: ” + plaintext);

    // Encrypt the cleartext
    byte[] ciphertext = null;
    ciphertext = rsaCipher.doFinal(cleartext);
    System.out.println(”the encrypted text is: ” + new String(ciphertext));

    // Initialize the same cipher for decryption
    rsaCipher.init(Cipher.DECRYPT_MODE, priv);

    // Decrypt the ciphertext
    byte[] cleartext1 = rsaCipher.doFinal(ciphertext);
    System.out.println(”the final cleartext is: ” + new String(cleartext1));

    }
    }

    thks for this posts …i gained good knowledge of cryptography through this..

  92. Douglas Says:

    Hello guys I test the last code posted with jdk1.4, 1.5 and 1.6 and this throw me an error fatal error classLoadeer (541)

    classLoadeer (…)classLoadeer (…)classLoadeer (…)classLoadeer (…)

    thanks

  93. Saurabh Says:

    im working with j2me …
    for encypting sms im using RSA
    how do i let other user know about my public key ??

  94. Aviran Mordo Says:

    You just publish the key anyway you want, usually create a page where users can download your public key

  95. Saurabh Says:

    thnx for ur reply ..
    u r too good man
    but
    i m not understandin this concept perfectly…
    i mean how to generate public n private key
    shall i take just two random keys ??
    im using paswword for protecting msg.
    how to use that password two generate public n private key??
    plz help me out …

  96. Aviran Mordo Says:

    Password and keys are two different things. If you use a password then you don’t need to use keys. Usually a key is something that you generate automatically, give the public key to your users via file or a BASE64 string, and keep the private key to yourself so you can decrypt the messages from your users

  97. Supreme Says:

    How would you send the BASE64 encoded string over the network to another host using a socket connection. I have been trying to do this with no luck as I always get a type mismatch.

  98. Aviran Mordo Says:

    you might want to take a look at this: Make HTTP POST Or GET Request From Java

  99. Alehandro Says:

    Hello Aviran. I am looking for help in coding the following in Java. Kindly assist .
    a sample application which implements:
    • Two principals A and B
    • An Authentication Server
    Two scenarios should be coded. In each instance separate processes should be
    established to execute on separate machines using TCP or UDP:
    • Mutual authentication and key exchange based on the use of the
    Authentication Server (where each of the principals A and B share a
    master key with the AS).
    • Mutual authentication and key exchange based on the use of Public Keys,
    where A and B each have a public and private key pair. You may assume
    that the public key of the other party is available locally on a “public key” ring / store.
    I will appreciate any assistance offered. Thanks

  100. Alehandro Says:

    Hello Aviran. I am looking for help in coding the following.

    a sample application which implements:
    • Two principals A and B
    • An Authentication Server
    Two scenarios should be coded. In each instance separate processes should be
    established to execute on separate machines using TCP or UDP:
    • Mutual authentication and key exchange based on the use of the
    Authentication Server (where each of the principals A and B share a
    master key with the AS).
    • Mutual authentication and key exchange based on the use of Public Keys,
    where A and B each have a public and private key pair. You may assume
    that the public key of the other party is available locally on a “public key”ring / store.

    Bouncy Catle and RSA algorithm in ECB mode with PKCS1 padding

    Thanks you

  101. Alehandro Says:

    Hi. Can anyone help me out with the earlier posted task. Thanks

  102. Milan Says:

    I m getting the following problem whil running a java program.
    I have installed JDK 1.5 in my system and set my class path accordingly.While compilling a program it is being compiled well,but wile trying to run it,it is showing the error

    “Exception in thread “main” java.lang.UnsupportedClassVersionError: milan (Unsupported major.minor version 49.0)”

    Then I checked Javac -version and it is showing java 1.3 and for Java version it is java 1.5…..But in my system i dont have java 1.3….

    so please help me in resolving this problem…Thanks in advance..

  103. Aviran Mordo Says:

    This is not java problem. This usually happens because of a classpath error. Recompile all your classes and make sure your JRE and JDK are the same version,

  104. shaayesta Says:

    hi.. i have tried this code for decryption of java.. i hv the encrypt.ect as my encrypted msq file and another file which has the product of p&q (i.e. n.ect).. plz tell what is the problem with this code..

    import java.awt.*;
    import java.awt.event.*;
    import java.math.BigInteger;
    import java.util.Random;
    import java.io.*;

    public class RSADec extends frame implements ActionListener
    {
    Button decryptButton;
    TextArea mta;
    TextField tf;
    Label l1,l2,l3;
    Panel tPanel, bPanel;
    String mtext ,d =null ,n=null,e=null;

    public void actionPerformed(ActionEvent event)
    {
    try{

    FileInputStream fin = new FileInputStream(”encrypt.ect”);
    BufferedInputStream bin = new BufferedInputStream(fin);
    StringBuffer buf = new StringBuffer();

    int ch=0;
    while((ch=bin.read())>-1)
    {
    buf.append((char)ch);
    }
    mta.setText(buf.toString());
    mtext = new BigInteger(mta.getText().getBytes()).toString();

    FileInputStream fin1 = new FileInputStream(”n.ect”); BufferedInputStream bin1 = new BufferedInputStream(fin1);
    StringBuffer buf1 = new StringBuffer();
    int ch1=0;
    while((ch1=bin1.read())>-1)
    {
    buf1.append((char)ch1);
    }
    n=buf1.toString();
    //System.out.println(n);

    //javax.swing.JOptionPane.showMessageDialog(null,”modulo : ” + n + ” enc : ” +mta.getText());

    d=tf.getText();
    mta.setText(decrypt(new BigInteger(mtext),new BigInteger(d),new BigInteger(n)).toString());
    //javax.swing.JOptionPane.showMessageDialog(null,mta.getText());
    TextArea plainTextArea = new TextArea();
    //tPanel.add(plainTextArea);
    //plainTextArea.setText(new String(new BigInteger(mta.getText()).toByteArray()));
    }
    catch(IOException e){
    System.out.println(e);
    }
    catch(NumberFormatException e)
    {
    System.out.println(”number ” + e);
    }
    }

    public static void main(String g[])
    {
    new RSADec();
    }

    public RSADec()
    {
    createGUI();
    pack();
    setVisible(true);

    }

    public void createGUI()
    {
    setLayout(new FlowLayout());
    l1 = new Label(”Private “);
    l2 = new Label();
    l3 = new Label(”enter text here “);
    decryptButton= new Button(” Decrypt “);
    mta = new TextArea(30,30);
    tPanel = new Panel();
    tPanel.add(l1);
    tPanel.add(l2);
    tPanel.add(l3);
    tPanel.add(mta);
    tPanel.add(decryptButton);
    decryptButton.addActionListener(this);
    tf = new TextField(30);
    tPanel.add(tf);
    add(tPanel);
    }

    BigInteger decrypt(BigInteger c, BigInteger d, BigInteger n) {
    BigInteger m, bitmask;
    m = new BigInteger(”0″);
    int i = 0;
    bitmask = (new BigInteger(”2″)).pow(n.bitLength()).subtract(new BigInteger(”1″));
    while (c.compareTo(bitmask) == 1) {
    m = c.and(bitmask).modPow(d,n).shiftLeft(i*(n.bitLength()-1)).or(m);
    c = c.shiftRight(n.bitLength());
    i = i+1;
    }
    m = c.modPow(d,n).shiftLeft(i*(n.bitLength()-1)).or(m);
    javax.swing.JOptionPane.showMessageDialog(this,m);
    return m;
    }
    }

Leave a Reply

You must have Javascript enabled in order to submit comments.

All fields are optional (except comment).
Some comments may be held for moderation (depends on spam filter) and not show up immediately.
Links will automatically get rel="nofollow" attribute to deter spammers.

Powered by WordPress