Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 7.29 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Encrypt and Decrypt String using RSA algorithm
  2. package service;
  3.  
  4. /**
  5.  *
  6.  * @author SiNiStEr
  7.  */
  8. import java.io.*;
  9. import java.security.*;
  10. import javax.crypto.*;
  11. import org.apache.commons.codec.binary.Hex;
  12.  
  13. class EDCRYPT {
  14.  
  15. public static void main(String args[]) throws Exception
  16.     {
  17. EDCRYPT ed= new EDCRYPT();
  18. System.out.print(ed.decrypt(ed.encrypt("Hello")));
  19. }
  20. public String encrypt(String plaintext) throws Exception{
  21.     Cipher cipher=null;
  22. PublicKey publicKey=null;
  23.         try {
  24.  
  25.             KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
  26.             SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
  27.             keygenerator.initialize(1024, random);
  28.  
  29.             KeyPair keypair = keygenerator.generateKeyPair();
  30.            // PrivateKey privateKey = keypair.getPrivate();
  31.              publicKey= keypair.getPublic();
  32.             cipher = Cipher.getInstance("RSA");
  33.         } catch (Exception e) {
  34.         }
  35.  
  36.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  37.         String st = "roseindia";
  38.         byte[] cleartext = null;
  39.         cleartext = st.getBytes("UTF-8");
  40.  
  41.     byte[] encrypted = blockCipherPublic(cleartext,Cipher.ENCRYPT_MODE);
  42. //return encrypted.toString();
  43.     char[] encryptedTranspherable = Hex.encodeHex(encrypted);
  44.     return new String(encryptedTranspherable);
  45. }
  46. ///////////////////////////////////////////////////////////////////////////////
  47.  
  48.  
  49. public String decrypt(String encrypted) throws Exception{
  50.   Cipher cipher=null;
  51. PrivateKey privateKey=null;
  52.         try {
  53.  
  54.             KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
  55.             SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
  56.             keygenerator.initialize(1024, random);
  57.  
  58.             KeyPair keypair = keygenerator.generateKeyPair();
  59.             privateKey = keypair.getPrivate();
  60.            //  publicKey= keypair.getPublic();
  61.             cipher = Cipher.getInstance("RSA");
  62.         } catch (Exception e) {
  63.         }
  64.  
  65.         cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  66.     byte[] bts = Hex.decodeHex(encrypted.toCharArray());
  67.  
  68.     byte[] decrypted = blockCipherPrivate(bts,Cipher.DECRYPT_MODE);
  69.  
  70.     return new String(decrypted,"UTF-8");
  71. }
  72.  
  73. ////////////////////////////////////////////////////////////////////////////////////
  74.  
  75. private byte[] blockCipherPublic(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
  76.     // string initialize 2 buffers.
  77.     // scrambled will hold intermediate results
  78.    Cipher cipher=Cipher.getInstance("RSA");
  79. PublicKey publicKey=null;
  80.         try {
  81.  
  82.             KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
  83.             SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
  84.             keygenerator.initialize(1024, random);
  85.  
  86.             KeyPair keypair = keygenerator.generateKeyPair();
  87.            // PrivateKey privateKey = keypair.getPrivate();
  88.              publicKey= keypair.getPublic();
  89.  
  90.         } catch (Exception e) {
  91.         }
  92.     byte[] scrambled = new byte[0];
  93.  
  94.     // toReturn will hold the total result
  95.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  96.  
  97.     byte[] toReturn = new byte[0];
  98.     // if we encrypt we use 100 byte long blocks. Decryption requires 128 byte long blocks (because of RSA)
  99.     int length = (mode == Cipher.ENCRYPT_MODE)? 100 : 128;
  100.  
  101.     // another buffer. this one will hold the bytes that have to be modified in this step
  102.     byte[] buffer = new byte[length];
  103.  
  104.     for (int i=0; i< bytes.length; i++){
  105.  
  106.         // if we filled our buffer array we have our block ready for de- or encryption
  107.         if ((i > 0) && (i % length == 0)){
  108.             //execute the operation
  109.             scrambled = cipher.doFinal(buffer);
  110.             // add the result to our total result.
  111.             toReturn = append(toReturn,scrambled);
  112.             // here we calculate the length of the next buffer required
  113.             int newlength = length;
  114.  
  115.             // if newlength would be longer than remaining bytes in the bytes array we shorten it.
  116.             if (i + length > bytes.length) {
  117.                  newlength = bytes.length - i;
  118.             }
  119.             // clean the buffer array
  120.             buffer = new byte[newlength];
  121.         }
  122.         // copy byte into our buffer.
  123.         buffer[i%length] = bytes[i];
  124.     }
  125.         scrambled = cipher.doFinal(buffer);
  126.  
  127.     // final step before we can return the modified data.
  128.     toReturn = append(toReturn,scrambled);
  129.  
  130.     return toReturn;
  131.  
  132.  
  133. }
  134.  
  135. ///////////////////////////////////////////////////////////////////////////////////////
  136.  
  137. private byte[] blockCipherPrivate(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
  138.     // string initialize 2 buffers.
  139.     // scrambled will hold intermediate results
  140.    Cipher cipher=Cipher.getInstance("RSA");
  141. PrivateKey privateKey=null;
  142.         try {
  143.  
  144.             KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
  145.             SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
  146.             keygenerator.initialize(1024, random);
  147.  
  148.             KeyPair keypair = keygenerator.generateKeyPair();
  149.            privateKey = keypair.getPrivate();
  150.             // publicKey= keypair.getPublic();
  151.  
  152.         } catch (Exception e) {
  153.         }
  154.     byte[] scrambled = new byte[0];
  155.  
  156.     // toReturn will hold the total result
  157.         cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  158.  
  159.     byte[] toReturn = new byte[0];
  160.     // if we encrypt we use 100 byte long blocks. Decryption requires 128 byte long blocks (because of RSA)
  161.     int length = (mode == Cipher.ENCRYPT_MODE)? 100 : 128;
  162.  
  163.     // another buffer. this one will hold the bytes that have to be modified in this step
  164.     byte[] buffer = new byte[length];
  165.  
  166.     for (int i=0; i< bytes.length; i++){
  167.  
  168.         // if we filled our buffer array we have our block ready for de- or encryption
  169.         if ((i > 0) && (i % length == 0)){
  170.             //execute the operation
  171.             scrambled = cipher.doFinal(buffer);
  172.             // add the result to our total result.
  173.             toReturn = append(toReturn,scrambled);
  174.             // here we calculate the length of the next buffer required
  175.             int newlength = length;
  176.  
  177.             // if newlength would be longer than remaining bytes in the bytes array we shorten it.
  178.             if (i + length > bytes.length) {
  179.                  newlength = bytes.length - i;
  180.             }
  181.             // clean the buffer array
  182.             buffer = new byte[newlength];
  183.         }
  184.         // copy byte into our buffer.
  185.         buffer[i%length] = bytes[i];
  186.     }
  187.         scrambled = cipher.doFinal(buffer);
  188.  
  189.     // final step before we can return the modified data.
  190.     toReturn = append(toReturn,scrambled);
  191.  
  192.     return toReturn;
  193.  
  194.  
  195. }
  196.  
  197.  
  198. /////////////////////////////////////////////////////////////////////////////////////
  199. private byte[] append(byte[] prefix, byte[] suffix){
  200.     byte[] toReturn = new byte[prefix.length + suffix.length];
  201.     for (int i=0; i< prefix.length; i++){
  202.         toReturn[i] = prefix[i];
  203.     }
  204.     for (int i=0; i< suffix.length; i++){
  205.         toReturn[i+prefix.length] = suffix[i];
  206.     }
  207.     return toReturn;
  208. }
  209.  
  210. //////////////////////////////////////////////////////////////////////////////////////////
  211. }
  212.        
  213. Cipher cipher=Cipher.getInstance("RSA"); and it should work