Using RSA encryption with Java
With the increase awareness to security the demand for securing data is rising. Fortunately Java provides pretty good tools that can help developers encrypt and decrypt data.
One of the most popular encryption is called RSA encryption. Named after its inventors, Ron Rivest, Adi Shamir and Leonard Adleman, RSA encryption transforms the number “char” into the number “cipher” with the formula
cipher = char^e (mod n)
The numbers e and n are the two numbers you create and publish. They are your “public key.” The number char can be simply the digital value of a block of ASCII characters. The formula says: multiply the number char by itself e times, then divide the result by the number n and save only the remainder. The remainder that we have called cipher is the encrypted representation of char.
Using the two numbers you have published, anyone can scramble a message and send it to you. You are the only one who can unscramble it; not even the sender of the message can decrypt the ciphertext.
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.
Since I couldn’t find any good examples that use Java with RSA, we’ll build a nice RSAEncryptUtil class that you can use as a reference for using RSA encryption (you can download the full source code here).
The first thing we need to do is to define the algorithm that we want to use.
protected static final String ALGORITHM = "RSA";
Then as stated before we’ll need to add Bouncy Castle as our RSA provider. In order to do that we’ll write an Init method for our class
/**
* Init java security to add BouncyCastle as an RSA provider
*/
public static void init()
{Security.addProvider(new BouncyCastleProvider());
}
To generate what is called private and public keys, Java provides us with a simple to use KeyPairGenerator class. The java.security.KeyPairGenerator generates the two keys that are returned in a java.security.KeyPair object.
/**
* Generate key which contains a pair of privae and public key using 1024 bytes
* @return key pair
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKey() throws NoSuchAlgorithmException
{KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
return key;}
Tweet
|
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;
}
}
January 27th, 2009 at 5:38 am
hi ,
i have problem in that code whea we compile that it cant show error but at run time it can.t work
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);
}
}
January 27th, 2009 at 8:16 am
Un-comment the BouncyCastleProvider code segments.
February 1st, 2009 at 1:51 pm
Hello,
I have the following problem.I am using this example.I generate keys of 2048.When I do the first encryption I get a byte[] of 256.And I want to do a second encryption but I get that too much data block.I tried to make a new array of 250 but I get the same message.Is the padding necessary in this case??How to do it??Please any help….
February 2nd, 2009 at 4:04 am
Block size should be 245. 2048/8 - 11 = 245
February 3rd, 2009 at 10:08 am
I do the following:
byte[] rawstring = “ADASDADS”.getBytes(”UTF-8″);
byte [] temp = RSA_ED.encrypt(rawstring, …getPrivate().getEncoded(),1);
byte [] temp2 = RSA_ED.encrypt(temp,….getPublic().getEncoded() ,2);
byte [] temp3 = RSA_ED.decrypt(temp2,….getPrivate().getEncoded(),1 );
byte [] temp4 = RSA_ED.decrypt(temp3, ….getPublic().getEncoded(),2);
RSA_ED is my clas with your methods.
With 2048 keys.And in the second encryption I use no padding.Sometimes I get:input too large for RSA cipher
But not always.Why?I have to do a sign and encrypt procedure.May you tell me how to do this?If I break the blocks how to do the decryption?
I read the http://forums.sun.com/thread.jspa?threadID=532116&messageID=2568882#2568882 but it says to use bigger key.
February 4th, 2009 at 3:36 am
If you’ll download the code I attached from the above article you can see an example of a method to encrypt a file. Basically you break a file into blocks and encrypt each block. You do decryption the same way (just download the code and you’ll see both methods.
Just so you know RSA is not an optimal way to encrypt large amount of data. If you plan to do so it is better if you use AES encryption for the data and RSA to encrypt the AES key.
February 9th, 2009 at 9:57 am
Hi Aviran
Excellent Article!
Is there any javascript code similar to this Java code for RSA?
February 9th, 2009 at 11:25 am
I really don’t know, never had to use one
February 16th, 2009 at 6:16 pm
@Ezhill
re: javascript
take a look here:
http://www-cs-students.stanford.edu/~tjw/jsbn/
March 1st, 2009 at 12:05 am
Hello,
Nice…
File decryption fails when using a key of bit size 2048 & 4096 to encrypt/decrypt. File encryption works ok. The file size doesn’t seem to matter. I’m running some tests hence the large keys… Also know that symmetric encryption is better for files..
See the exception thrown below:
javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at RSAEncryptUtil.decrypt(RSAEncryptUtil.java:88)
at RSAEncryptUtil.encryptDecryptFile(RSAEncryptUtil.java:229)
at RSAEncryptUtil.decryptFile(RSAEncryptUtil.java:185)
at RSAEncryptUtil.main(RSAEncryptUtil.java:293)
April 20th, 2009 at 7:03 pm
HI, someone please help asap ….
I need to write a program that allows user to type a message and that message is ecnrypted and stored in a file.
The encrypted file is then decrypted and then displayed using the same program using RSA security.
PLease help asap. Thanks
July 14th, 2009 at 6:09 am
plz, help me in video steganography concept i want a code for rsa encryption,decryption and key genaration and one more, how the encrypted data embedded to video file.
July 14th, 2009 at 4:41 pm
Hi,
As part of one of my projects I should encrypt a given file with the thawte public key. The certificate is valid. So I use the following code to encrypt the input file:
int readed;
byte[] readBytes = new byte[117];
FileInputStream fis = new FileInputStream(”path to der file”);
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance(”X.509″);
Certificate cer = cf.generateCertificate(bis);
RSAPublicKey publicKey = (RSAPublicKey)cer.getPublicKey();
FileOutputStream fileOutputStream = new FileOutputStream(”output file”);
FileInputStream inFile = new FileInputStream(”the file to be encrypted”);
Cipher rsa = Cipher.getInstance(”RSA”);
rsa.init(Cipher.ENCRYPT_MODE, publicKey);
while ((readed = inFile.read(readBytes)) != -1)
{
fileOutputStream.write(rsa.doFinal(readBytes));
}
bis.close();
fis.close();
inFile.close();
fileOutputStream.flush();
fileOutputStream.close();
My problem is that if I run the encryption twice, the generated results are not one and the same.
Can you help me with the problem?
August 6th, 2009 at 5:29 pm
please, i need a complete java source code for rsa encryption/decryption and rsa public/private key generation.
thanks.
August 7th, 2009 at 12:52 pm
Test submit
August 7th, 2009 at 12:53 pm
Here it is:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPublicKey;
import java.util.Enumeration;
import java.util.Properties;
import javax.crypto.Cipher;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
FileInputStream inFile = new FileInputStream(”./in/MyFile”);
FileOutputStream fileOutputStream = null;
Cipher rsa = null;
FileInputStream fis = new FileInputStream(”./certificates/MyCert.cer”);
BufferedInputStream bis = new BufferedInputStream(fis);
fileOutputStream = new FileOutputStream(”./out/MyFile.enc”);
Security.addProvider(new BouncyCastleProvider());
CertificateFactory cf = CertificateFactory.getInstance(”X.509″);
Certificate cer = cf.generateCertificate(bis);
RSAPublicKey publicKey = (RSAPublicKey) cer.getPublicKey();
rsa = Cipher.getInstance(”RSA/ECB/PKCS1Padding”, “BC”);
rsa.init(Cipher.ENCRYPT_MODE, publicKey);
int readed;
byte[] readBytes = new byte[rsa.getBlockSize()];
while ((readed = inFile.read(readBytes)) != -1)
{
byte[] tmp = rsa.doFinal(copyBytes(readBytes, readed));
fileOutputStream.write(tmp);
}
bis.close();
fis.close();
inFile.close();
fileOutputStream.flush();
fileOutputStream.close();
August 7th, 2009 at 12:53 pm
String pass = “test”;
KeyStore keyStore = KeyStore.getInstance(”PKCS12″);
FileInputStream keyStoreStream = new FileInputStream(”./certificates/MyCert.pfx”);
char[] password = pass.toCharArray();
keyStore.load(keyStoreStream, password);
PrivateKeyAndCertificationChain privateKeyAndCertificationChain =getPrivateKeyAndCertChain(keyStore, pass);
PrivateKey pk = privateKeyAndCertificationChain.mPrivateKey;
rsa.init(Cipher.DECRYPT_MODE, pk);
FileInputStream encFile = new FileInputStream(”./out/MyFile.enc”);
FileOutputStream decrFile=new FileOutputStream(”./out/MyFile.dec”);
readed = 0;
readBytes = new byte[rsa.getBlockSize()];
while ((readed = encFile.read(readBytes)) != -1)
{
decrFile.write(rsa.doFinal(copyBytes(readBytes, readed)));
}
decrFile.flush();
decrFile.close();
encFile.close();
—-
public static byte[] copyBytes(byte[] arr, int length)
{
byte[] newArr = null;
if (arr.length == length)
{
newArr = arr;
}
else
{
newArr = new byte[length];
for (int i = 0; i < length; i++)
{
newArr[i] = (byte) arr[i];
}
}
return newArr;
}
–
You will need BouncyCastleProvider - bcprov-jdk14-143.jar.
If you have the certificate, you can use Internet Explorer and/or Firefox to export the public and private keys.
Public Key should be in DER format.
In order to create a keystore file, use this article:
http://www.herongyang.com/jtool/jca_keytool.html
I hope this will help.
September 17th, 2009 at 2:58 pm
FYI, no one should be using the RSA algorithm to encrypt files. Instead:
1. generate a symmetric key (16 random bytes for AES128, for example)
2. use the public key to encrypt (”wrap”) the symmetric key
3. use the symmetric key to encrypt the data
4. place the wrapped symmetric key in a header of the ciphertext file
Thanks for the Java tips-
September 17th, 2009 at 3:09 pm
This is true!
September 26th, 2009 at 1:58 am
DEAR FRIENDS THANKS FOR THIS DETAILS NEXT I WILL ENTERED WITH SOLUTION
September 30th, 2009 at 10:56 pm
THANXS 4 all
thank sri krishna , you solve my problem
October 9th, 2009 at 6:43 am
Hello,
I have few questions :
1) It has been mentioned that SunJCE provides implementation for RSA. (JDK 1.6). Do we still need to use BouncyCastle.
2) I have private and public key in XML format generated using VB.net program. But I have a requirement to decrypt using Java. How to do this ? Would JCE supports this ?
3) Can you provide sample java Code to sign(ature) encrypted (RSA) text and then decrypt (RSA) and verify the signature.
This is very urgent and your help would be greatly appreciated.
Thanks,
Sarath.
November 12th, 2009 at 6:24 am
HI Aviran,
I wrote dis program…its working fine but i want to store encrypted data in seperate .txt file and decrypt by taking dat encrypted .txt file…i stored encrypted data in one file and i am decrypting dat file but it giving error… and i dont know about public key and private key in rsa algorithm..
plz give me any idea about dis?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EncDec extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
byte[] fileArray=null;
Cipher rsaCipher;
PrivateKey priv;
try{
response.setContentType(”text/html”);
PrintWriter out = response.getWriter();
out.println(”");
out.print(”");
String s=request.getParameter(”Encrypt”);
if(s.equals(”Encrypt”))
{
/* Generate a RSA key pair */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”RSA”);
SecureRandom random = SecureRandom.getInstance(”SHA1PRNG”,”SUN”);
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
/* Create the cipher */
rsaCipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);
// Initialize the cipher for encryption
rsaCipher.init(Cipher.ENCRYPT_MODE, pub);
String strLine;
String fileData=”";
String s1=request.getParameter(”file”);
FileInputStream f = new FileInputStream(new File(s1));
BufferedReader br = new BufferedReader(new InputStreamReader(f));
out.println(”");
out.println(”selected file:“);
while ((strLine = br.readLine()) != null)
{
out.println (strLine+”");
fileData+=(strLine+”\r\n”);
}
fileArray = fileData.getBytes();
br.close();
// Encrypt the text
byte [] ciphertext = new byte[10000];
//byte[] ciphertext = null;
ciphertext = rsaCipher.doFinal(fileArray);
out.println(” Encrypted text is:“+”");
for(int i=0; i<ciphertext.length; i++)
out.println(ciphertext[i]);
// Initialize the same cipher for decryption
rsaCipher.init(Cipher.DECRYPT_MODE, priv);
// Decrypt the ciphertext
byte[] orgtext = rsaCipher.doFinal(ciphertext);
//String s2=new String(orgtext);
String s2=”";
out.println(”");
out.println(”Decrypted text:“+”");
//out.println(”\r\n”.getBytes()[0]);
for(int i=0; i<orgtext.length; i++)
{
if(orgtext[i]==13)
s2+=(char)orgtext[i]+”";
else
s2+=(char)orgtext[i];
}
out.println(s2);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
November 12th, 2009 at 6:26 am
The error is..
exception in thread “main” javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
at com.sun.crypto.provider.RSACipher.a(DashoA12275)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA12275)
at javax.crypto.Cipher.doFinal(DashoA12275)
November 16th, 2009 at 2:36 am
Please, i am writing a project on implementation of Rivest-Shamir-Adleman(RSA) algorithm on local area network(LAN).But the JAVA program i wrote refused to work. please, can anyone help me with this.The program is given below.
/**
* @(#)trial.java
*
* trial application
*
* @author
* @version 1.00 2009/9/14
*/
// Package DataEncryption
//My_RSA.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class My_RSA extends JFrame {
private Container container;
private JFrame iFrame,jFrame, kFrame;
private GridBagLayout layout;
private GridBagConstraints constraints;
private JTextField nField, dField;
private JTextArea messageArea, cypherArea, plainArea,keysArea;
private JScrollPane messagescroll, cypherScroll, plainScroll;
private JButton readButton, sendButton, okButton, cancelButton;
private JPanel jPanel, nPanel,dPanel, okPanel,myPanel, mePanel,
statusPanel, progressPanel,cancelPanel;
private JPanel boardPanel1, boardPanel2, cypherPanel,plainPanel,
messagePanel, readPanel, sendPanel;
private JLabel emptyLabel, jLabel, nLabel, dLabel, dumLabel1, dumLabel2,
statusLabel;
private JLabel emptyLabel1, emptyLabel2 , emptyLabel3, emptyLabel4;
private JPanel emptyPanel, emptyPanel1, emptyPanel2, emptyPanel3,
emptyPanel4;
private String message = “”, plaintext = “”, cyphertext = “”, publish = “”;
private long d, e, m, n, p, q;
private final JProgressBar current = new JProgressBar(0, 100);
private KeyGenerator gen;
private Encryption enc;
private Decryption dec;
private Sending go;
public My_RSA()
{
Super(”RSA Encryption System”);
Container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
constraints = new GridBagConstraints();
gen = new KeyGenerator();
kFrame = new JFrame(”Sending…”);
mePanel = new JPanel();
mePanel.setLayout(layout);
progressPanel = new JPanel();
progressPanel.add(current);
cancelPanel = new JPanel();
statusPanel = new JPanel();
statusPanel = new JLabel(” From A to B”);
statusPanel.add(statusLabel);
cancelButton = new JButton(”cancel”);
cancelButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event)
{
Current.setValue(0);
kFrame.setVisible(false);
}
}
);
Current.setSize(100, 5);
cancelPanel.add(cancelButton);
emptyLabel1 = new JLabel(”");
emptyLabel2 = new JLabel(”");
emptyLabel3 = new JLabel(”");
emptyLabel4 = new JLabel(”");
emptyPanel1 = new JPanel();
emptyPanel2 = new JPanel();
emptyPanel3 = new JPanel();
emptyPanel4= new JPanel();
readPanel = new JPanel();
sendPanel = new JPanel();
messagePanel = new JPanel();
cypherPanel = new JPanel();
plainPanel = new JPanel();
boardPanel1 = new JPanel();
boardPanel1.setLayout(new FlowLayout());
boardPanel2 = new JPanel();
boardPanel2.setLayout(new FlowLayout());
messageArea = new JTextArea(5,60);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setFont(new Font(”Monospaced”, Font.PLAIN, 12));
messageArea.setEditable(true);
cypherArea = new JTextArea(20,20);
cypherArea.setLineWrap(true);
cypherArea.setWrapStyleWord(true);
cypherArea.setFont(new Font(” Serif”, Font.PLAIN, 12));
cypherArea.setEditable(false);
plainArea = new JTextArea(20,22);
plainArea.setLineWrap(true);
plainArea.setWrapStyleWord(true);
plainArea.setFont(new Font(” Monospaced”, Font.PLAIN, 12));
plainArea.setEditable(false);
messageScroll = new JScrollPane(messageArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEVER);
cypherScroll = new JScrollPane(cypherArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
plainScroll = new JScrollPane(plainArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
readButton = new JButton(”read>>>”);
readButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event)
{
secretKey();
}
}
);
sendButton = new JButton(”send”);
sendButton.addActionListener(
new ActionListner() {
public void actionPerformed(ActionEvent event)
{
kFrame.setVisible(false);
publish = “”;
do {
p = gen.primeNumber();
}while(!(p > 10) || !(p < 26) );
do {
q = gen.primeNumber();
}while( (q 2) );
n = p*q;
m = (p-1) * (q-1);
e = gen.coprime(m);
d = gen.find_d(m,e);
message = messageArea.getText();
enc = new Encryption(message);
cyphertext = enc.encrypt(e,n);
publish_Keys();
kFrame.setVisible(true);
go = newSending(cyphertext,kFrame,iFrame,
cypherArea, current, container);
go.start();
kFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
container.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
}
);
cypherPanel.add(cypherScroll);
cypherPanel.setBorder(BorderFactory.createTitledBorder(”cyphertext”));
readPanel.add(readButton);
plainPanel.add(plainScroll);
plainPanel.setBorder(BorderFactory.createTitledBorder(”recovered plaintext”));
messagePanel.add(messageScroll);
sendPanel.add(sendButton);
emptyPanel1.add(emptyLabel1);
emptyPanel2.add(emptyLabel2);
emptyPanel3.add(emptyLabel3);
emptyPanel4.add(emptyLabel4);
boardPanel1.add(cypherPanel);
boardPanel1.add(readPanel);
boardPanel1.add(plainPanel);
boardPanel1.setBorder(BorderFactory.createTitledBorder(”incoming message”));
boardPanel2.add(messagePanel);
boardPanel2.add(sendPanel);
boardPanel2.setBorder(BorderFactory.createTitledBorder(”outgoing message”));
constraints.fill = GridBagConstraints.BOTH;
addComponent3(emptyPanel1, 0, 0, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent3(emptyPanel2, 1, 0, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent3(statusPanel, 2, 0, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent3(progressPanel, 3, 0, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent3(cancelPanel, 3, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent(emptyPanel1, 0, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent(emptyPanel1, 0, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent(boardPanel1, 1, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent(emptyPanel2, 2, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent(emptyPanel3, 3, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent(emptyPanel4, 4, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent(boardPanel2, 5, 1, 1, 1);
kFrame.getContentPane().add(mePanel, BorderLayout.CENTER);
kFrame.setResizable(false);
kFrame.setSize(310,150);
kFrame.setVisible(false);
kFrame.setLocation(270, 390);
setResizable(false);
setSize(550,680);
setVisible(true);
setLocation(250,42);
}
private void publish_Keys()
{
iFrame = new JFrame(”Publishing Keys”);
publish += “\n PUBLIC KEY:\n (n, e) = (”+n+”, “+e+”)”;
publish += “\n \n SECRET KEY:\n (n, d) = (”+n+”, “+d+”)”;
keysArea = new JTextArea();
keysArea.setFont( new Font(”Monospaced”, Font.BOLD, 14) );
keysArea.setEditable(false);
keysArea.setText(publish);
iFrame.getContentPane().add(new JScrollPane(keysArea),
Borderlayout.CENTER);
iFrame.setResizable(false);
iFrame.setSize(210, 220);
iFrame.setVisible(false);
iFrame.setLocation(570, 390);
}
private void secretKey()
{
jFrame = new JFrame(”SECRET KEY”);
myPanel = new JPanel();
jPanel = new JPanel();
nPanel = new JPanel();
dPanel = new JPanel();
emptyPanel = new JPanel();
okPanel = new JPanel();
emptyLabel = new JLabel(”");
nLabel = new JLabel(”n: “);
dLabel = new JLabel(”d: “);
dumLabel1 = new JLabel(” “);
jLabel = new JLabel(”Enter the Secret Key:”);
jPanel.add(jlabel);
okButton = new JButton(”OK”);
okButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event)
{
jFrame.setVisible(false);
n = Long.parseLong(nField.getText());
d = Long.parseLong(dField.getText());
cyphertext = cypherArea.getText();
dec = new Decryption(cyphertext);
plaintext = dec.decrypt(d,n);
plainArea.setText(plaintext);
}
}
);
myPanel.setLayout(layout);
nField = new JTextField(10);
nField.setFont(new Font(”Monospaced” , Font.PLAIN, 14));
dField = new JTextField(10);
dField.setFont(new Font(”Monospaced” , Font.PLAIN, 14));
nPanel.setLayout(new FlowLayout());
nPanel.add(nLabel);
nPanel.add(nField);
dPanel.setLayout(new FlowLayout());
dPanel.add(dLabel);
dPanel.add(dField);
emptyPanel.add(emptyLabel);
okPanel.add(okButton);
constraints.fill = GridBagConstraints.BOTH;
addComponent2(jPanel, 0, 0, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent2(nPanel, 1, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent2(dPanel, 2, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent2(emptyPanel, 3, 1, 1, 1);
constraints.fill = GridBagConstraints.BOTH;
addComponent2(okButton, 4, 1, 1, 1);
jFrame.getContentPane().add(myPanel);
jFrame.setLocation(438, 360);
jFrame.setResizable(false);
jFrame.setSize(200, 220);
jFrame.setVisible(true);
}
private void addComponent(Component component, int row, int column, int width,
int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
container.add(component);
}
private void addComponent2(Component component, int row, int column, int width, int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
myPanel.add(component);
}
private void addComponent3(Component component, int row, int column, int width, int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
mePanel.add(component);
}
public static void main(String args[])
{
My_RSA app = new My_RSA();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
/**
* @(#)encryption.java
*
* encryption application
*
* @author
* @version 1.00 2003/5/21
*/
//encryption.java
public class Encryption {
private String Msg, encrypted =”";
private long encrypt_char[], encrypted_message[];
private int leadingZeros;
private long exponent, divide;
private final int BITSIZE = 10;
public Encryption(string mesag)
{
Msg = mesag;
encrypt_char = new long[Msg.lenght()];
encrypted_message = new long[Msg.length()];
}
public String encrypt(long exponent, long divide)
{
for(int i = 0; i < Msg.length(); i++) {
Encrypt_char[i] = (long)Msg.charAt(i);
Encrypted_message[i] =(long)Math.pow((double)encrypt_char[i],(double)expont) % divide;
Encrypted += convertToBinary(encrypted_message[i]);
}
Return encrypted;
}
private String convertToBinary(long num)
{
String s1 =”",s2 = “”;
do {
s1 += (num % 2);
num /= 2;
} while(num != 0 );
if( s1.length()<BITSIZE )
leadingZeros=(BITSIZE-s1.length());
else
leadingZeros = 0;
if( leadingZeros != 0) {
for(int i = 1; s1= 0; i–)
s2 += s1.charAt(i);
return s2;
}
}
/**
* @(#)Decryption.java
*
* Decryption application
*
* @author
* @version 1.00 2003/5/21
*/
//package Datadecryption
//Decryption.java
public class Decryption {
private long decrypted_message [], recovered[];
private int length, lowerIndex, upperIndex;
private long h, y, z, P;
private final int BITSIZE = 10;
private String encrypted[], decrypted =”";
public void Decrypted(String encrypted_message)
{
length = encrypted_message.length() / BITSIZE;
encrypted = new String[length];
decrypted_message = new long[length];
recovered = new long[length];
lowerIndex = 0;
upperIndex = BITSIZE;
for(int i = 0; i < length; i++) {
encrypted[i] = encrypted_message.substring(lowerIndex, upperIndex);
recovered[i] = convertFromBinary(encrypted[i]);
lowerIndex = upperIndex;
upperIndex += BITSIZE;
}
}
private long recoveredPlaintext(long x)
{
h = 1;
do {
if( (y %2) != 0) {
h *= x;
y–;
}
else{
x = (long)Math.pow((double)x, (double)2) % z;
y /= 2;
}
}while(y != 1);
P = (h*x) % z;
return P;
}
public String decrypt(long exp, long divisor)
{
System.out.print(” \n\n”);
for(int i = 0; i < length; i++) {
y = exp;
z = divisor;
decrypted_message[i] = recoveredPlaintext(recovered[i]);
}
return decrypted;
}
private long convertFromBinary(String S)
{
long converted = 0;
int bit = 0, power = S.length() - 1;
for(int i = 0; i < S. length(); i++) {
bit = Character.digit(S.charAt(i), 2);
converted +=(long)bit*(long)Math.pow((double)2,(double)power);
power–;
}
return converted;
}
}
/**
* @(#)KeyGenerator.java
*
* KeyGenerator application
*
* @author
* @version 1.00 2003/5/21
*/
//package DataEncryption
// keyGenerator.java
public class KeyGenerator {
private long length;
private long d,e, rem, num;
private int i, count, counter;
public KeyGenerator ()
{
}
public long primeNumber()
{
do {
num = (long) (Math.random()*40);
} while(isPrime(num)==false);
return num;
}
public long coprime(long limit)
{
e = 2;
do {
e++;
}while(isPrime(e) == false || (limit % e) == 0);
return e;
}
public long find_d(long numb, long div)
{
Counter = 0;
do {
d = (1 + ((long)counter*number)) / div;
rem = (1 + ((long)counter*number)) % div;
counter++;
}while( integerSolution() == false );
return d;
}
private Boolean isPrime(long number)
{
Count = 0;
if(number != 1) {
for(i = 1; i <= number; i++)
if( (number % i) == 0)
count++;
}
if(count == 2 )
return true;
else
return false;
}
private Boolean integerSolution()
{
if( rem == 0 )
return true;
else
return false;
}
}
/**
* @(#)Sending.java
*
* Sending application
*
* .event.@author
* @version 1.00 2003/5/21
*/
//Package NeutralNetwork
//Sending.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
public class Sending extends Thread {
private static int DELAY;
private static final int BITSIZE = 10;
private String Mesag;
private JFrame theframe, keyFrame;
private JTextArea myArea;
private JProgressBar progressBar;
private Container container;
public Sending(String cypherMsg,JFrame xFrame,JFrame yFrame, JTextArea theArea, JProgressBar bar, Container contentPane) {
Mesag = cypherMsg;
theframe = xFrame;
keyFrame = yFrame;
myArea = theArea;
progressBar = bar;
container = contentPane;
}
public void run() {
int minimum = progressBar.getMinimum();
int maximum = progressBar.getMaximum();
DELAY = Mesag.length() / BITSIZE;
Runnable runner = new Runnable() {
public void run() {
int value = progressBar.getValue();
progressBar.setValue(value+1);
if( progressBar.getValue() == progressBar.getMaximum() )
{
theframe.setVisible(false);
myArea.setText(Mesag);
keyFrame.setVisible(true);
container.setCursor(null); //turn off wait cursor
Toolkit.getDefaultToolkit().beep();
progressBar.setValue(0);
}
}
};
for (int i=minimum; i<maximum; i++)
{
try
{
SwingUtilities.invokeAndWait(runner);
// Our task each step is to just sleep
Thread.sleep((int)(Math.random()*DELAY));
}
catch (InterruptedException e) { }
catch (InvocationTargetException ex) { }
}
} //end ‘Runnable’
} // end method ‘Run’
November 17th, 2009 at 5:37 pm
Hello guys, please how can i get JAVA source code for implementation of RSA Algorithm on Local area Network (LAN). Thanks.
December 2nd, 2009 at 5:38 am
I stored my public and private keys in “.txt” file, I retrieve them and they become string now.
how can I use them to do encryption/decryption??
please help me ASAP
thanks in advanced:)
December 10th, 2009 at 2:44 am
HI aviran,
In the example you have mentioned ways to encode a key or the data as strings, But if i hwant to use the private key to decrypt the data, how will i go by it?
I know i can use a base64Decoder to decode the string back into byte arrays, but how do i regain the key from the byte array?
Looking forward to your advice..
Thanks,
George
January 12th, 2010 at 1:02 pm
The implementation that you have suggest is an excellent resource.
Just want to confirm if there is a later version of this with new releases of Java itself and BouncyCastle API.
Your version dates back to 2004 and probably thats quiet some eons back
Thanks,
January 12th, 2010 at 10:44 pm
Wow Aviran,
Thanks so much for providing this example. This isnt a half implemented wreck like a lot of the examples I have seen are. I greatly appreciate the time you must have taken to put this together. Your programming style is very nice.
January 18th, 2010 at 7:30 pm
Hi everyone, I’m not much of a programmer myself, so i was wondering can anybody help me make an email client program where you can implement the DSA algorihm inside so that the email client can append digital signatures to emails while also decrypt it? any URL links that corresponds will help me a lot. Thank you for your help.
January 21st, 2010 at 12:05 am
ok i want to implement the RSA algorithm in J2ME .i dont want to use any third party s/w.Can anyone help? thanks in advance
January 21st, 2010 at 11:39 am
thanx a lot mate, i m so much thankful to you! God Bless You!
February 17th, 2010 at 3:26 am
hi.
i m luking for java code implementaion of RSA algo
my project uses oracle DB
my aim is to get record from user SAY ” T”, encrypy it and save it in ORACLE DB in encrypted form only.
Then i want to retrieve the same record.. so enter the record say” T”
but this time i m getting it encrypted in different form. so my records are not matching with DB records and i m unable to retrieve..
give me FULL source code
February 17th, 2010 at 3:23 pm
Really useful i was searching for RSA algorithm …. how it works etc i got alll information ineeded
February 17th, 2010 at 4:11 pm
To Taiseen:
Does this help? :
http://www.oracle.com/technology/oramag/oracle/05-sep/o55security.html
February 23rd, 2010 at 10:08 am
i encrypted and decrpted txt file and it worked just fine but when i tried to encrypt and decrypt word or PDF file the decrypted file in case of the file was currapted
and in case of pdf the pages were white altough the size of the file was equal the size of the original file
can anyone help me please
thx
March 11th, 2010 at 9:57 am
import java.sql.*;
import java.math.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.lang.String.*;
public class ppdm2
{
public int p,q,n,e,d,phi;
int num[]=new int[200];
int enc[]=new int[200];
int i,j,nof;
static String val;
int dec[] = new int[200];
public ppdm2()
{ p=17;
q=11;
n=0;
e=7;
d=23;
phi=0;
i=0;
j = 0;
nof = 0;
}
public String RSA(String val)
{
//System.out.println(”enter value of p and q\n”);
n=p*q;
phi=(p-1)*(q-1);
for(i=2;i<phi;i++)
{
if(gcd(i,phi)!=1)
break;
}
e=i;
for(i=2;i<phi;i++)
{
if((e*i-1)%phi==1)
break;
}
d=i;
for(i=0;i<val.length();i++)
{
num[i]=val.charAt(i);
nof=val.length();
}
for(i=0;i<nof;i++)
{
enc[i]=1;
for(j=0;j<e;j++)
enc[i]=(enc[i]*num[i])%n;
}
for(i=0;i<nof;i++)
{
dec[i]=1;
for(j=0;j<d;j++)
dec[i]=(dec[i]*val.charAt(i))%n;
}
char temp[]=new char[enc.length];
for (int x = 0; x < enc.length; x++) temp[x] =(char)enc[x];
return new String(temp);
}
public int gcd(int m,int n)
{
int r;
while(n!=0)
{
r=m%n;
m=n;
n=r;
}
return m;
}
public static void main(String args[]) throws IOException
{
String msg[];
String url = “jdbc:odbc:ppdm”;
Connection con = null;
try {
String driver = “sun.jdbc.odbc.JdbcOdbcDriver”;
Class.forName(driver);
}
catch( Exception e )
{
System.out.println(”Failed to load mSQL driver.”);
return;
}
/*
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println(”File Not Found”);
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(”Usage: ShowFile File”);
return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
}
*/
ppdm2 pp=new ppdm2();
try
{
con = DriverManager.getConnection(url);
PreparedStatement select = con.prepareStatement(”SELECT * FROM pdb”,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet result = select.executeQuery();
System.out.println(”Got results:”);
while(result.next( ))
{ // process results one row at a time
int key;
//String val;
key = result.getInt(1);
if( result.wasNull( ) )
{
key = -1;
}
val = result.getString(2);
if( result.wasNull( ) )
{
val = null;
}
result.updateString(2,pp.RSA(val));
result.updateRow();
System.out.println(”key = ” + key);
System.out.println(”val = ” + val);
//result.Commit();
}
}
catch( Exception e )
{
e.printStackTrace( );
}
finally
{
if( con != null )
{
try
{ con.close( ); }
catch( Exception e )
{ e.printStackTrace( ); }
}
}
}
}
hey this wht i’ve written.. but iam not able 2 recover the original data in DB once i encrypt.. plz help.. its urgent
March 30th, 2010 at 5:25 am
Dear Aviran,
Thanks for solving many of the programming nightmares associated with Cryptography. Please, i need a complete java implementation of RSA algorithm that takes into account the 512, 1024, etc modulus. This is to enable me perform a comparative analysis with the Elliptic curve equivalent.
April 15th, 2010 at 1:34 pm
This is really a good article to solve your RSA encryption
task with strings/files and manipulate as you want..
thanks..Aviran
June 16th, 2010 at 12:46 am
It is helpful
July 2nd, 2010 at 5:30 am
Hi,
Thanks lot the code, it was very helpful.
I have a problem and I need some help plz
public static String encodeBASE64(byte[] bytes)
{
BASE64Encoder b64 = new BASE64Encoder();
return b64.encode(bytes);
}
public static byte[] decodeBASE64(String text) throws IOException
{
BASE64Decoder b64 = new BASE64Decoder();
byte[] teste = b64.decodeBuffer(text);
return b64.decodeBuffer(text);
}
If I encode this String “Hello World !!!! ”
and when try to get this string back I get this output
“Hello/World/////”
How can i resolve this problem?
Thanks
July 3rd, 2010 at 11:55 pm
I don’t know why you are getting this error, check your imports, or try to find another base64 implementation
July 4th, 2010 at 8:19 am
I´m using this import
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
July 30th, 2010 at 11:56 am
frnd i need one urgent help..i need one mini project with its full source code..plz help me….very kind to u
October 23rd, 2010 at 8:47 pm
Hi there, I’m trying to generate some RSA keys in an android program.
I’ve put some of the code from your example into a class that will generate the keys, but am having some difficulty.
Keep getting ‘Unhandled exception type NoSuchAlgorithmException’ whenever calling the ‘generateKeys’ function.
What am I doing wrong?
import android.app.Activity;
import android.os.Bundle;
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import org.bouncycastle.jce.provider.*;
import org.bouncycastle.*;
public class GenerateKeys extends Activity {
protected static final String ALGORITHM = “RSA”;
public static void init()
{
Security.addProvider(new BouncyCastleProvider());
}
/**
* Generate key which contains a pair of privae and public key using 1024 bytes
* @return key pair
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKey() throws NoSuchAlgorithmException
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
return key;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); {
init();
KeyPair myKeys = generateKey();
}
}
}
December 7th, 2010 at 1:01 pm
hey friends i need a java code for rsa encryotion please can anyone help me please i need so
i need when i enter a plain text
the program can to translate to cipher text
and when cipher text is created again program can traslate again to plain text
December 18th, 2010 at 5:39 pm
Hi,
Thanks for the example. But I have a problem that’s driving me crazy.
As far as I know, when I generate an RSA key pair, with 1024 bits, it uses blocks with size 128. What about this? :
I ensured that the byte array buf’s length is 128. When I call cipher.doFinal(buf), it throws the exception “input too large for RSA cipher”. Any ideas?
December 19th, 2010 at 10:20 pm
hey all…
I work in J2ME. I still do not know how to encrypt the input using RSA, if the input value more than the modulus value? can you tell me about it……?
December 29th, 2010 at 4:19 am
Fantastic, Your code is so helpful for me.
And these following discussion is useful.
Thanks so much.
December 29th, 2010 at 7:17 am
Brilliant thanks
January 23rd, 2011 at 11:16 pm
Hi,
Nice article and I really learn a lot from it. I had use your code with RSA and it definitely works fine. I’d also made an attempt to try it with ElGamal, but I got an error when trying to encrypt files with large sizes (my files ranges from 1byte up to 1mb, all are of textfiles). I had use the following to generate my keypair:
public static KeyPair generateKey() throws Exception
{
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”ElGamal”,”BC”);
keyGen.initialize(256);
KeyPair key = keyGen.generateKeyPair();
return key;
}
January 23rd, 2011 at 11:29 pm
Hi,
Nice article and I really learn a lot from it. I had use your code with RSA and it definitely works fine. I’d also made an attempt to try it with ElGamal, but I got an error when trying to encrypt files with large sizes (my files ranges from 1byte up to 1mb, all are of textfiles).
I had use the following to generate my keypair:
public static KeyPair generateKey() throws Exception
{
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(”ElGamal”,”BC”);
keyGen.initialize(256);
KeyPair key = keyGen.generateKeyPair();
return key;
}
and
public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
{
….
…
…
byte[] buf = cipherMode == Cipher.ENCRYPT_MODE? new byte[100] : new byte[128];
//I don’t know what value should I replace with these, can someone suggest me about that?
// I want to know size limit for ElGamal
…
…
}
Here’s the exception I got:
org.bouncycastle.crypto.DataLengthException: attempt to process message too long for cipher
Please could someone help me with this? I really need a solution badly!
Thanks,
January 25th, 2011 at 10:15 am
this code is very is to implement the security.i love this website.
January 29th, 2011 at 11:41 am
please help me how i run a java program which imports javax. i have a tomcat software but i have a problem with running pgm.any one help me please ,
help me please
April 26th, 2011 at 2:27 am
Hello,
Nice…
File decryption fails when using a key of bit size 2048 & 4096 to encrypt/decrypt. File encryption works ok. The file size doesn’t seem to matter. I’m running some tests hence the large keys… Also know that symmetric encryption is better for files..
See the exception thrown below:
javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at RSAEncryptUtil.decrypt(RSAEncryptUtil.java:88)
at RSAEncryptUtil.encryptDecryptFile(RSAEncryptUtil.java:229)
at RSAEncryptUtil.decryptFile(RSAEncryptUtil.java:185)
at RSAEncryptUtil.main(RSAEncryptUtil.java:293)
April 26th, 2011 at 6:00 am
HI All,
I found the solution, kyesize/8 will solve the problem
Regards,
Selva.
April 27th, 2011 at 6:57 am
I have a working version of the RSA for a byte array.
I can convert a string to a byte array as byte[] b1 = s1.getBytes;
But Afer encryption and decryption, I can recover the encrypted bye array, ie b1, but cannot extract the string s1 back.
s2 = b2.toString(); doesn’t work.
April 28th, 2011 at 4:31 am
Dear all,
I am doing an RSA encryyption in Mobile Agent Aglets. But I’ve been facing a problem for a week now. I can’t get Bouncycastle to work,
I imported it, and I added the “Security.addProvider(new BouncyCastleProvider()); ” in my code, and I modified the java.security file in my JRE, but I still get this error:
java.lang.InternalError: cannot create instance of org.bouncycastle.jce.provider
.symmetric.AES$Mappings : java.security.AccessControlException: access denied (j
ava.security.SecurityPermission putProviderProperty.BC)AverageSlave: Failed to s
end result to master.
at org.bouncycastle.jce.provider.BouncyCastleProvider.loadAlgorithms(Unk
nown Source)AverageSlave: null
at org.bouncycastle.jce.provider.BouncyCastleProvider.setup(Unknown Sour
ce)
at org.bouncycastle.jce.provider.BouncyCastleProvider.access$000(Unknown
Source)
at org.bouncycastle.jce.provider.BouncyCastleProvider$1.run(Unknown Sour
ce)
at java.security.AccessController.doPrivileged(Native Method)
at org.bouncycastle.jce.provider.BouncyCastleProvider.(Unknown Sou
rce)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:501)
at java.lang.Class.newInstance0(Class.java:350)
at java.lang.Class.newInstance(Class.java:303)
at sun.security.jca.ProviderConfig$3.run(ProviderConfig.java:240)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.jca.ProviderConfig.doLoadProvider(ProviderConfig.java:22
5)
at sun.security.jca.ProviderConfig.getProvider(ProviderConfig.java:205)
at sun.security.jca.ProviderList.getProvider(ProviderList.java:205)
at sun.security.jca.ProviderList$ServiceList.tryGet(ProviderList.java:40
6)
at sun.security.jca.ProviderList$ServiceList.access$200(ProviderList.jav
a:348)
at sun.security.jca.ProviderList$ServiceList$1.hasNext(ProviderList.java
:458)
at javax.crypto.Cipher.getInstance(DashoA12275)
at examples.myaglets.MasterAvg.rsaEncrypt(MasterAvg.java:111)
at examples.myaglets.MasterAvg.handleMessage(MasterAvg.java:290)
at com.ibm.aglets.MessageImpl.handle(Unknown Source)
at com.ibm.aglets.AgletThread.run(Unknown Source)
Can any one please help me!!! is there is a way to fix this? or is there is another way to do RSA coding?
Thanks
April 30th, 2011 at 10:08 am
@Mo - I’m not sure but did you try using an obfuscator?
April 30th, 2011 at 5:41 pm
@Ajitesh: thanks for ur reply, but what is obfuscator? can u explain more pleasE?
May 3rd, 2011 at 11:26 pm
hii..
i need a code for file encryption and decryption using…
DES
blowfish
please give the code Thanks for RSA…
August 1st, 2011 at 2:17 pm
hi
August 24th, 2011 at 8:05 am
You are absolutly rigth! Fortunately Java provides pretty good tools and Java hosting is no more expensive. Check http://www.jvmhost.com - I could not find better deal these days
August 24th, 2011 at 2:50 pm
hey i want client server programming code with authentication where RSA or DES algorithm used for encription & decription in java. so plz help me to give me full source.
September 30th, 2011 at 10:02 am
Thanks buddy.
Really helped.
October 19th, 2011 at 9:24 am
Hi Aviran,
Refer to the below API which got from your program:
public static void encryptFile(String srcFileName, String destFileName, PublicKey key) throws Exception
How to pass the PublicKey parameter to encrypt the file ?
I am using keystore file and it contains the keys.
Thanks in advance
October 19th, 2011 at 11:37 pm
Hi Aviran,
Please igonre my prev question. I have found the solution. Do you have sample code for Sign, Verify, SignEncrypt and VerifyDecrypt ?
October 20th, 2011 at 3:45 am
@Khan - Sorry I don’t have any sample code
October 24th, 2011 at 3:29 am
Hi Aviran,
Thanks for your reply.
I need to do the following testing:
1. Generation of keys using ‘RSA’ algorithm
2. Encryption and Decryption using 3DES algorithm.
3. Need to use the Bouncycastle provider.
Do u have any sample code for the above ? Or Can we use RSAEncryptUtil. java with minimum changes for Encryption and Decryption using 3DES algorithm?
October 25th, 2011 at 4:55 am
Hi Aviran,
I’m awaiting for ur reply for the question no 174. Pls reply me since its urgent.
Thks
October 25th, 2011 at 2:34 pm
You can use the RSAEncryptUtil freely.
Unfortunately I do not have code samples for you that I can share other than what is already in RSAEncryptUtil.
October 26th, 2011 at 11:33 pm
Ok. No problem. I have done it thru other program. It would be nice if i done thru changing RSAEncryptUtil. I like your example program. In case if you change the program to fulfill the above requirement pls share with us.
January 30th, 2012 at 2:00 am
hai,i’m doing project in bluetooth file transfer using client server connection.now my part is to provide security using digital signatures please help me with codings in j2me.very urgent
January 30th, 2012 at 2:02 am
i think it will be better to use RSA along with SHA1 algorithm please send me the codings very urgent..
January 30th, 2012 at 2:03 am
j2me codings for digital signature ?????
March 14th, 2012 at 2:13 am
how to read PrivateKey from a file that is password protected?
April 12th, 2012 at 7:45 pm
Hi… This site is very helpful. the code which has been put up is working fine. I need to make a secure message board.
I need codes which can help me implement client-server authentication and once the clients are connected using tcp sockets, then a client should be able to encrypt a message locally and send it to the server. The server waits for the receiver to log in. once logged in, it just pushes the message and the client decrypts locally.
April 29th, 2012 at 11:11 am
Well, you’re reading memory address, not the content of byte array.
You can fix like this:
String originalText= new String(clearText1);
System.out.println(”Decrypted text:”+ clearText1);
Done!
May 23rd, 2012 at 6:56 am
ive started to visit this site several times now we should state that i have found it quite exeptional actually. keep writing! :p
June 1st, 2012 at 8:10 am
i have a problem with this coding..in my netbeans library do not have package for log4j and bouncycastle.jce.provider.*,
can anyone give me any downloads links for this two package?kindly appreciate if someone can help me because i have downloads a few but it is not functional.
July 27th, 2012 at 9:08 am
Hi I am working in a project where I need to migrate the JDK from 1.4 to 1.6. Now we have a code where the below has been used.
private static com.bt.util.logging.base64.BASE64Encoder b64E = new com.bt.util.logging.base64.BASE64Encoder();
In 1.4 it was fine but when I tried to compile it in jdk6 that time the below compilation error is coimg.
com.bt.util cannot be resolved to a type
Currently commons-codec-1.3.jar was used but I replaced it with commons-codec-1.6 [latest one], but still the same error is coming. can anybody pls help me here? what is the commons codec compatible version for jdk 6?
July 27th, 2012 at 9:12 am
fika…for log4j you can refer http://logging.apache.org/log4j/1.2/download.html
and for bouncycastle you can refer http://www.bouncycastle.org/latest_releases.html
July 28th, 2012 at 2:59 am
BASE64Encoder comes standard in jdk under sun.misc.BASE64Encoder
November 29th, 2012 at 1:45 pm
Hi,
I have replaced bouncy castle provider with JsafeJCE, got an exception saying InvalidKeySpecException
java.security.spec.InvalidKeySpecException: Could not decode key from BER. (Invalid encoding: expected tag not there.)
com.rsa.cryptoj.f.eW.b(Unknown Source)
com.rsa.cryptoj.f.eW.engineGeneratePrivate(Unknown Source)
java.security.KeyFactory.generatePrivate(KeyFactory.java:336)
Same code works fine with BouncyCastle…
below is the snippet
KeyFactory fact = KeyFactory.getInstance(”RSA”,JsafeJCE.BASE_PROVIDER_NAME);
PrivateKey privateKey = fact.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString.getBytes())) );
PublicKey publicKey = certificate.getPublicKey();
Any Help is appreciated… Thanks in advance
January 3rd, 2013 at 8:15 am
i have a question. Is Probable prime applicable to J2ME???bec. i find it difficult in encoding the codes for encryption using RSA. Please help. it will be use for my thesis
May 24th, 2013 at 6:17 am
getting and illegal parameter error out here
December 22nd, 2013 at 7:23 pm
pls sir/ma, i kindly need your help on the project topic : digital signature system design and implementation using RSA Algorithm. I will b glad if u can please help me on this, thanks
June 7th, 2014 at 8:59 am
hi
please help me.
im new in coding
how can i fix all of _log = Logger.getLogger ERROR??????????
June 24th, 2014 at 6:05 am
Thanks for your sharing.It is appreciated very much. And I wonder whether there are some differences between the java code 128 barcode generator I am testing these days and the one you mentioned above? Do you have any ideas about it? Or any good suggestion? Thanks in advance.
September 26th, 2014 at 1:25 pm
Hi Aviran,
Thanks for the good article but i am facing a strange issue. I am using JsafeJCE provider to decrypt the encrypted message i am receiving from another application. My code works fine with jre1.7_25 on windows but with same jre it does not work on linux. I get the following error
Caused by: java.lang.SecurityException: JCE cannot authenticate the provider JsafeJCE
at javax.crypto.Cipher.getInstance(Cipher.java:642)
at javax.crypto.Cipher.getInstance(Cipher.java:580)
at com.db.jms.test.CipherSpec.createCipher(CipherSpec.java:118)
at com.db.jms.test.SimpleDecryptor.createCipher(SimpleDecryptor.java:54)
at com.db.jms.test.MySimpleDecryptor.getCipher(MySimpleDecryptor.java:33)
at com.db.jms.test.MySimpleDecryptor.decrypt(MySimpleDecryptor.java:56)
I have set the provider in the java.security file in the jre/lib/security/java.security file and have increased the priority as well. Still i am getting the error. Can you help please?
April 2nd, 2015 at 3:47 am
Can u pls tell me how to display byte array to string while decryption