Using RSA encryption with Java
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;}











(5 votes)
RSS Feeds 



October 16th, 2004 at 7:54 am
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)
November 30th, 2004 at 7:40 pm
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
December 7th, 2004 at 10:47 am
You need to replace the line
Cipher rsaCipher = Cipher.getInstance("RSA");with
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");December 10th, 2004 at 12:05 am
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!!
July 17th, 2005 at 7:07 pm
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.
August 5th, 2005 at 2:27 am
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!!
August 5th, 2005 at 3:35 pm
Dhanya, The answer is in the forum.
Click here
August 9th, 2005 at 6:26 am
It works.
Thanks for giving me a reply,
August 29th, 2005 at 1:32 pm
Can U please help me
I need the code for encryption and decryption in java using the RSA algorithm.
August 29th, 2005 at 1:38 pm
At the end of the article (page 3) you have a link to download the code
September 24th, 2005 at 10:23 am
i need encryption and decryption algorithm in java
October 6th, 2005 at 9:03 am
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
October 10th, 2005 at 10:11 am
Thanks very much for the code.
November 29th, 2005 at 8:11 pm
how to encrypt the message which is longer than 128 bytes with RSA?
November 29th, 2005 at 11:07 pm
Check out the file encryption for example, basically you do it in blocks
December 6th, 2005 at 3:22 am
A very good Java RSA example
December 6th, 2005 at 3:23 am
A very good Java RSA example
December 9th, 2005 at 7:04 am
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.
January 3rd, 2006 at 10:05 am
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.
January 5th, 2006 at 7:39 pm
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?
January 17th, 2006 at 9:49 am
Hello,
In order to run this example, “iaik_jce.jar” is needed.
How can I find this jar file?
January 24th, 2006 at 8:28 am
try this:
new String(plaintext, “8859_1″);
//where byte[] cleartext = null;
February 7th, 2006 at 6:31 am
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
February 21st, 2006 at 3:11 am
Are there any copyright restrictions for me to use your RSAEncryptUtil class in my system?
February 21st, 2006 at 7:52 am
Vijay: You are free to use this code without any restrictions.
February 22nd, 2006 at 2:33 am
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…
February 23rd, 2006 at 8:58 pm
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.
February 26th, 2006 at 1:50 pm
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?
March 3rd, 2006 at 4:59 am
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..
March 3rd, 2006 at 5:46 am
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…
March 14th, 2006 at 7:44 am
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
March 18th, 2006 at 3:57 am
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.
March 29th, 2006 at 3:42 am
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)
March 29th, 2006 at 10:58 am
“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.”
April 5th, 2006 at 3:12 pm
How will i run this code please reply??
April 5th, 2006 at 3:22 pm
From where will i get all the packages and how will i run this code plz explain in detail like from cmd javac etc…
April 5th, 2006 at 5:02 pm
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.
April 8th, 2006 at 9:57 pm
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?
April 11th, 2006 at 10:21 am
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
April 17th, 2006 at 2:49 am
u have been a great help
thanks
gaurav
April 21st, 2006 at 3:39 am
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
April 21st, 2006 at 8:49 am
You need to add a provider (bouncyCastle)
Security.addProvider(new BouncyCastleProvider());
May 13th, 2006 at 6:55 am
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!
May 21st, 2006 at 4:57 am
Implement each of the following

1-Miler-Rabin Algorithm(chap
2-The extended Euclid’s algorithm (chap
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
June 15th, 2006 at 1:47 pm
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.
June 15th, 2006 at 1:49 pm
plzzzzzz helpme out as soon as possible. u can help me out at vijju_31@rediffmail.com. it is really verrrrrrry urgent for me.
June 16th, 2006 at 3:53 pm
Thks man!!! very usefull!!!
June 21st, 2006 at 2:21 am
Good explanation and great example. Thank you very much!
August 2nd, 2006 at 1:30 am
i have to encrypt and decrypt the folder using DES algoritm, please help me
September 7th, 2006 at 3:06 am
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
September 14th, 2006 at 3:20 am
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);
}
}
September 14th, 2006 at 2:07 pm
You need to add a provider. Java does not provide RSA Algorithm, this is why you need the BouncyCastle
September 15th, 2006 at 1:22 am
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
September 15th, 2006 at 1:26 pm
Make sure you have the bouncy castle jar file in your class path
September 16th, 2006 at 6:31 pm
When I encrypt a String “bubba” it decrypts to “bubb”, I have followed the guide very carefully, any hints?
October 18th, 2006 at 1:52 am
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
October 18th, 2006 at 9:34 am
The answer to both questions is yes, although I’m not 100% sure about switching the private and public keys roles
November 12th, 2006 at 4:18 am
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.
November 12th, 2006 at 4:20 am
Sorry the files are ssh_host_rsa_key and ssh_host_rsa_key.pub !!!
November 12th, 2006 at 8:23 am
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.
November 21st, 2006 at 8:02 am
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.
April 26th, 2007 at 4:03 pm
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
April 26th, 2007 at 5:12 pm
I can only guess that you are missing the Bouncy Castle jar file from your classpath
April 26th, 2007 at 11:33 pm
where can i get Bouncy castle jar file?
April 26th, 2007 at 11:36 pm
There is a link in the first page of the article, but here it is again http://www.bouncycastle.org/latest_releases.html
April 26th, 2007 at 11:53 pm
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
April 27th, 2007 at 1:04 pm
This is hard to guess, but I think that some of your jar files do not match the JVM version you are using
April 27th, 2007 at 2:04 pm
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
April 27th, 2007 at 6:25 pm
Did you read the article ? Look at the init method above
April 28th, 2007 at 9:34 pm
hi
Do u know how to convert (RSA)publickey to byte array and viceversa?
Thanks
May 23rd, 2007 at 5:27 am
Good post,thank you for your great words!
June 19th, 2007 at 5:35 am
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 .
June 19th, 2007 at 9:36 am
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)
July 10th, 2007 at 4:44 am
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
September 1st, 2007 at 6:48 pm
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
September 1st, 2007 at 7:04 pm
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
January 9th, 2008 at 10:56 pm
Confused
January 15th, 2008 at 8:49 pm
Please post the corect code!!! I`m so confused……
January 25th, 2008 at 11:16 pm
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..
January 27th, 2008 at 1:21 am
Just store the key in a database or file, and use it next time
January 28th, 2008 at 8:05 am
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
January 29th, 2008 at 3:11 pm
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
February 7th, 2008 at 2:36 pm
Excellent! Thank you.
March 4th, 2008 at 10:29 am
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:(
March 4th, 2008 at 11:14 am
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);
}
}
March 4th, 2008 at 3:51 pm
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);
March 20th, 2008 at 7:08 am
heh tanx a lot..
i got d output:)
April 1st, 2008 at 2:02 am
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
April 2nd, 2008 at 6:23 am
Change:
Cipher cipher = Cipher.getInstance(”RSA/None/PKCS1Padding”);
To
Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);
April 2nd, 2008 at 10:45 am
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
April 4th, 2008 at 7:43 am
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..
April 10th, 2008 at 12:43 pm
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
April 12th, 2008 at 2:18 pm
im working with j2me …
for encypting sms im using RSA
how do i let other user know about my public key ??
April 13th, 2008 at 12:43 am
You just publish the key anyway you want, usually create a page where users can download your public key
April 13th, 2008 at 9:36 am
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 …
April 15th, 2008 at 2:02 am
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
May 11th, 2008 at 12:40 pm
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.
May 12th, 2008 at 2:04 am
you might want to take a look at this: Make HTTP POST Or GET Request From Java
June 19th, 2008 at 9:24 am
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
June 19th, 2008 at 9:37 am
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
July 9th, 2008 at 10:06 am
Hi. Can anyone help me out with the earlier posted task. Thanks
July 16th, 2008 at 2:35 am
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..
July 16th, 2008 at 6:21 am
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,
July 28th, 2008 at 12:52 am
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;
}
}