10/12/2004

Using RSA encryption with Java

Filed under: — By Aviran Mordo @ 10:53 am

So far we’ve created public and private keys, encrypted and decrypted messaged. But in order for this utility to be useful we need to be able to send and receive keys and messages. In many implementations you’ll need to do those actions without using bytes, but using strings. The first notion is just convert the byte array to a string object. But this will not work. In order to do that you’ll need to convert the bytes array to a Base64 string representation. Luckily for us this is a very easy task. The following methods will convert bytes to Base64 string and back.


/**
* Encode bytes array to BASE64 string
* @param bytes
* @return Encoded string
*/
private static String encodeBASE64(byte[] bytes)
{

    BASE64Encoder b64 = new BASE64Encoder();
    return b64.encode(bytes);

}

/**
* Decode BASE64 encoded string to bytes array
* @param text The string
* @return Bytes array
* @throws IOException
*/
private static byte[] decodeBASE64(String text) throws IOException
{

    BASE64Decoder b64 = new BASE64Decoder();
    return b64.decodeBuffer(text);

}

Now that we have the strings we can do anything we want with them: Save the key in a database, send the public key thru email, web page or any other method, send and receive encrypted messages and anything else you can think of.

One more useful task you would like to do is to be able to handle files. The problem with files (and large strings) is that RSA encryption data size limitations are slightly less than the key modulus size, depending on the actual padding scheme used (e.g. with 1024 bit (128 byte) RSA key, the size limit is 117 bytes for PKCS#1 v 1.5 padding. Hence in order to handle files we need to read and write the files in small blocks. In our example well use blocks of 100 bytes.


/**
* Encrypt and Decrypt files using 1024 RSA encryption
*
* @param srcFileName Source file name
* @param destFileName Destination file name
* @param key The key. For encryption this is the Private Key and for decryption this is the public key
* @param cipherMode Cipher Mode
* @throws Exception
*/
public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
{

    OutputStream outputWriter = null;
    InputStream inputReader = null;
    try
    {
    Cipher cipher = Cipher.getInstance(”RSA/ECB/PKCS1Padding”);
    String textLine = null;
    byte[] buf = cipherMode == Cipher.ENCRYPT_MODE? new byte[100] : new byte[128];
    int bufl;
    // init the Cipher object for Encryption…
    cipher.init(cipherMode, key);

    // start FileIO
    outputWriter = new FileOutputStream(destFileName);
    inputReader = new FileInputStream(srcFileName);
    while ( (bufl = inputReader.read(buf)) != -1)
    {

    byte[] encText = null;
    if (cipherMode == Cipher.ENCRYPT_MODE)
    {
    encText = encrypt(copyBytes(buf,bufl),(PublicKey)key);

}
else
{

    encText = decrypt(copyBytes(buf,bufl),(PrivateKey)key);

}
outputWriter.write(encText);
}
outputWriter.flush();
}
finally
{

    try
    {
    if (outputWriter != null)
    {
    outputWriter.close();

}
if (inputReader != null)
{

    inputReader.close();

}
}
catch (Exception e)
{

    // do nothing…

}
}
}

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;
}

I hope this article will help you make your first steps in to the encryption world. You can download the full source code, which includes some other convenient methods for you to work with.


 

Pages: 1 2 3

194 Responses to “Using RSA encryption with Java”

  1. Daniel S.G. Says:

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

    Regards from Spain.
    Danisg

    (Excuse my bad English)

  2. Bilal Says:

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

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

    class enc {

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

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

    BadPaddingException, NoSuchPaddingException {

    /* Generate a RSA key pair */

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

    keyGen.initialize(1024, random);

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

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

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

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

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

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

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

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

    this is the output i have:

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

    would u help ma plz
    thanks

  3. Aviran Says:

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

  4. Sarah Says:

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

  5. Daryl Says:

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

  6. Dhanya Says:

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

  7. Aviran Mordo Says:

    Dhanya, The answer is in the forum.

    Click here

  8. Dhanya Says:

    It works.
    Thanks for giving me a reply,

  9. mahesh Says:

    Can U please help me

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

  10. Aviran Mordo Says:

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

  11. radhakrishnan Says:

    i need encryption and decryption algorithm in java

  12. olumide olubuse Says:

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

    from
    ladoke akintola university of technology
    ogbomoso,oyo state
    nigeria

  13. Thanks Says:

    Thanks very much for the code.

  14. chakchai so-in Says:

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

  15. Aviran Mordo Says:

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

  16. Anonymous Says:

    A very good Java RSA example

  17. Sada Says:

    A very good Java RSA example

  18. Sivababu Says:

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

  19. mzhou Says:

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

    I got the following exception:

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

    Did I miss anything? Thanks.

  20. mad Says:

    doubt, methods getPublicKeyFromString and getPrivateKeyFromString have problems:

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

    Can U please help me?

  21. demirel Says:

    Hello,

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

  22. elpiloto Says:

    try this:

    new String(plaintext, “8859_1″);

    //where byte[] cleartext = null;

  23. Baiju from kerala,India Says:

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

    first u can use this code,

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

    Thanks daaaaaaaaaaaa

  24. Vijay M Says:

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

  25. Aviran Mordo Says:

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

  26. andika Says:

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

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

  27. Aviran Mordo Says:

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

  28. andika Says:

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

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

  29. vinodh Says:

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

  30. vinodh Says:

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

  31. jana Says:

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

    by jana

  32. arun prakash Says:

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

  33. rizwan Says:

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

  34. Joen S Says:

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

  35. Ronnit Says:

    How will i run this code please reply??

  36. ronnit Says:

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

  37. Aviran Mordo Says:

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

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

  38. Anonymous Says:

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

  39. jai shukla Says:

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

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

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

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

    Please help me asap.
    Thanks in advance

  40. gaurav Says:

    u have been a great help

    thanks
    gaurav

  41. K.Sankar Says:

    for Encrypt the data

    I gives

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

    but it returns the exception called

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

    at javax.crypto.Cipher.getInstance(DashoA6275)

    at enc.main(enc.java:30)

    please help me

  42. Aviran Mordo Says:

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

  43. assom issa Says:

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

  44. mustafa Says:

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

  45. vijaya Says:

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

  46. vijaya Says:

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

  47. Ivo Says:

    Thks man!!! very usefull!!!

  48. Helen Says:

    Good explanation and great example. Thank you very much!

  49. madhuri Says:

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

  50. Surya Says:

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

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

    Please mail me at suryakiranl@infotechsw.com

  51. muthukumar Says:

    hi all,

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

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

    at javax.crypto.Cipher.getInstance(DashoA6275)

    the code wil follw.

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

    class enc {

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

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

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

    /* Generate a RSA key pair */

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

    keyGen.initialize(1024, random);

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

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

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

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

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

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

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

  52. Anonymous Says:

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

  53. muthukumar Says:

    thanks anonymous…

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

    ” cannot resolve symbol : BoucyCastleProvider”.

    even though BouncyCastleProvider is already existed in my system.

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

    what should i do?

    regards,
    Muthukumar

  54. Aviran Mordo Says:

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

  55. mos Says:

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

  56. surya Says:

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

    please help me
    thanks in advance

  57. Aviran Mordo Says:

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

  58. Amir Says:

    Hey guys,

    Thanks for code…

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

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

    anyone has any idea?

    Thanks in advance for your reply!!

    Amir.

  59. Amir Says:

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

  60. Amir Says:

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

    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

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

    Thanks,

    Amir.

  61. Phil Quinlan Says:

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

    Hope this makes sense.

  62. jay Says:

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

  63. Aviran Mordo Says:

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

  64. jay Says:

    where can i get Bouncy castle jar file?

  65. Aviran Mordo Says:

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

  66. jay Says:

    Hi,

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

  67. Aviran Mordo Says:

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

  68. jay Says:

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

    Do i need to install this provider?
    Thanks

  69. Aviran Mordo Says:

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

  70. Anonymous Says:

    hi

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

  71. inflatable Says:

    Good post,thank you for your great words!

  72. Subhrajyoti Choudhury Says:

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

  73. Aviran Mordo Says:

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

  74. Rami Says:

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

    Thanks

  75. milan Says:

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

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

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

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

    Thanks,
    Milan

  76. milan Says:

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

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

    could you help me? thanks

  77. Jag Says:

    Confused

  78. Calin Says:

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

  79. target Says:

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

  80. Aviran Mordo Says:

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

  81. OneUser Says:

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

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

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

    Thanks in advance

  82. KeyJen Says:

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

    See

    http://www.cheersdata.com

  83. Rick Says:

    Excellent! Thank you.

  84. chindhu Says:

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

    class enc {

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

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

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

    /* Generate a RSA key pair */

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

    keyGen.initialize(1024, random);

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

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

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

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

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

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

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

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

    heh wenever i try bove pgm d output s lik

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

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

  85. chindhu Says:

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

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

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

    class enc {

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

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

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

    /* Generate a RSA key pair */

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

    keyGen.initialize(1024, random);

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

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

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

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

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

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

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

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

  86. Aviran Mordo Says:

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

  87. chindhu Says:

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

  88. sharad kumar Says:

    Hi All,

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

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

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

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

    public class RSA {

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

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

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

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

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

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

    }

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

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

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

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

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

    Any help will be highly appreciated.
    Kind Regards,
    sharad

  89. Anonymous Says:

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

  90. sharad kumar Says:

    Hi Anonymous,

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

    Any other clue ?
    regards,
    sharad

  91. sri krishna Says:

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

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

    class rsa{

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

    InvalidKeyException, IllegalBlockSizeException, NoSuchProviderException,

    BadPaddingException, NoSuchPaddingException {

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

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

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

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

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

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

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

    }
    }

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

  92. Douglas Says:

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

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

    thanks

  93. Saurabh Says:

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

  94. Aviran Mordo Says:

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

  95. Saurabh Says:

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

  96. Aviran Mordo Says:

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

  97. Supreme Says:

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

  98. Aviran Mordo Says:

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

  99. Alehandro Says:

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

  100. Alehandro Says:

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

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

    Bouncy Catle and RSA algorithm in ECB mode with PKCS1 padding

    Thanks you

  101. Alehandro Says:

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

  102. Milan Says:

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

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

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

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

  103. Aviran Mordo Says:

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

  104. shaayesta Says:

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

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

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

    public void actionPerformed(ActionEvent event)
    {
    try{

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

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

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

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

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

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

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

    }

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

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

  105. paritosh Says:

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

  106. Aviran Mordo Says:

    Un-comment the BouncyCastleProvider code segments.

  107. Alex Says:

    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….

  108. Aviran Mordo Says:

    Block size should be 245. 2048/8 - 11 = 245

  109. Alex Says:

    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.

  110. Aviran Mordo Says:

    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.

  111. Ezhil Says:

    Hi Aviran
    Excellent Article!
    Is there any javascript code similar to this Java code for RSA?

  112. Aviran Mordo Says:

    I really don’t know, never had to use one

  113. Cheeky Monkey Says:

    @Ezhill

    re: javascript
    take a look here:
    http://www-cs-students.stanford.edu/~tjw/jsbn/

  114. Meja Says:

    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)

  115. Kay Says:

    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

  116. murali Says:

    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.

  117. ost Says:

    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?

  118. Edward Philemon Says:

    please, i need a complete java source code for rsa encryption/decryption and rsa public/private key generation.
    thanks.

  119. ost Says:

    Test submit

  120. ost Says:

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

  121. ost Says:

    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.

  122. jared Says:

    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-

  123. ost Says:

    This is true! :-)

  124. ramesh.m Says:

    DEAR FRIENDS THANKS FOR THIS DETAILS NEXT I WILL ENTERED WITH SOLUTION

  125. smart_Mody Says:

    THANXS 4 all

    thank sri krishna , you solve my problem

  126. Sarath Says:

    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.

  127. sujatha Says:

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

  128. sujatha Says:

    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)

  129. kayode Says:

    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’

  130. kayode Says:

    Hello guys, please how can i get JAVA source code for implementation of RSA Algorithm on Local area Network (LAN). Thanks.

  131. Anonymous Says:

    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:)

  132. george Says:

    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

  133. Chetan Says:

    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,

  134. Charles Says:

    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.

  135. aadym Says:

    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.

  136. Anonymous Says:

    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

  137. moiezg Says:

    thanx a lot mate, i m so much thankful to you! God Bless You!

  138. Taiseen Says:

    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

  139. Balaji Says:

    Really useful i was searching for RSA algorithm …. how it works etc i got alll information ineeded

  140. ost Says:

    To Taiseen:
    Does this help? :
    http://www.oracle.com/technology/oramag/oracle/05-sep/o55security.html

  141. khalifa Says:

    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

  142. Saty Says:

    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

  143. Edward Philemon Says:

    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.

  144. Smruti Says:

    This is really a good article to solve your RSA encryption
    task with strings/files and manipulate as you want..
    thanks..Aviran

  145. Ripon Says:

    It is helpful

  146. Angelo Says:

    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

  147. Aviran Mordo Says:

    I don’t know why you are getting this error, check your imports, or try to find another base64 implementation

  148. Angelo Says:

    I´m using this import

    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;

  149. nishedh Says:

    frnd i need one urgent help..i need one mini project with its full source code..plz help me….very kind to u

  150. The Cageybee Says:

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

    }
    }
    }

  151. zhwan Says:

    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

  152. kadir Says:

    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?

  153. cino Says:

    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……?

  154. lendo.du Says:

    Fantastic, Your code is so helpful for me.

    And these following discussion is useful.

    Thanks so much.

  155. ebe Says:

    Brilliant thanks

  156. ceLax Says:

    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;

    }

  157. ceLax Says:

    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,

  158. avinash d.m Says:

    this code is very is to implement the security.i love this website.

  159. avinash dm Says:

    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

  160. Selvanayagam Says:

    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)

  161. Selvanayagam Says:

    HI All,

    I found the solution, kyesize/8 will solve the problem

    Regards,
    Selva.

  162. Aditya Says:

    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.

  163. Mo Says:

    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

  164. Ajitesh Says:

    @Mo - I’m not sure but did you try using an obfuscator?

  165. Mo Says:

    @Ajitesh: thanks for ur reply, but what is obfuscator? can u explain more pleasE?

  166. Vineet Sharma Says:

    hii..
    i need a code for file encryption and decryption using…

    DES
    blowfish

    please give the code Thanks for RSA…

  167. Shirley Blandy Says:

    hi

  168. Jonathan Elano Says:

    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

  169. pooja Says:

    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.

  170. Pedram Says:

    Thanks buddy.
    Really helped.

  171. Khan Says:

    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

  172. Khan Says:

    Hi Aviran,

    Please igonre my prev question. I have found the solution. Do you have sample code for Sign, Verify, SignEncrypt and VerifyDecrypt ?

  173. Aviran Mordo Says:

    @Khan - Sorry I don’t have any sample code

  174. Khan Says:

    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?

  175. Khan Says:

    Hi Aviran,

    I’m awaiting for ur reply for the question no 174. Pls reply me since its urgent.

    Thks

  176. Aviran Says:

    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.

  177. Khan Says:

    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.

  178. thangamps Says:

    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

  179. thangamps Says:

    i think it will be better to use RSA along with SHA1 algorithm please send me the codings very urgent..

  180. thangamps Says:

    j2me codings for digital signature ?????

  181. Anton Says:

    how to read PrivateKey from a file that is password protected?

  182. siva Says:

    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.

  183. OS Says:

    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!

  184. social media marketing Says:

    ive started to visit this site several times now we should state that i have found it quite exeptional actually. keep writing! :p

  185. fika Says:

    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.

  186. Subha Says:

    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?

  187. Subha Says:

    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

  188. Aviran Mordo Says:

    BASE64Encoder comes standard in jdk under sun.misc.BASE64Encoder

  189. Musab Says:

    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

  190. Hanzel Says:

    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

  191. keshav Says:

    getting and illegal parameter error out here

  192. dare Says:

    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

  193. mali Says:

    hi
    please help me.
    im new in coding
    how can i fix all of _log = Logger.getLogger ERROR??????????

  194. babard Says:

    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.

Leave a Reply

You must have Javascript enabled in order to submit comments.

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

Powered by WordPress