Encryption and Decryption in java


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;        
import javax.crypto.BadPaddingException;        
import javax.crypto.Cipher;        
import javax.crypto.IllegalBlockSizeException;        
import javax.crypto.KeyGenerator;        
import javax.crypto.NoSuchPaddingException;        
import javax.crypto.SecretKey;        
import javax.crypto.spec.SecretKeySpec;        
        
public class Demo {
        
   private SecretKey sk;
        
   private String mykey = "hellodeepsingh12"; // 16
             
   public Demo() {
        
      try {  
        
           // sk = KeyGenerator.getInstance("AES").generateKey();
        
           sk = new SecretKeySpec(mykey.getBytes(), "AES");
        
         } catch (Exception e) {
       
             System.out.println(e);
        
         }
        
      }
          
        
    private byte[] encrypt(String name) {
        
    byte[] cipherText = {};
        
       try {
        
         Cipher c = Cipher.getInstance("AES");
          
         c.init(Cipher.ENCRYPT_MODE, sk);
        
         byte[] input = name.getBytes();
        
         cipherText = c.doFinal(input);
        
         System.out.println(new String(cipherText));
        
          } catch (Exception e) {
        
           System.out.println(e);
        
          }
        
   return cipherText;
        
         }
             
        
    private void decrypt(byte[] data) {
        
       try {
        
         Cipher c1 = Cipher.getInstance("AES");
        
         c1.init(Cipher.DECRYPT_MODE, sk);
        
         byte[] dcipheredText = c1.doFinal(data);
        
         System.out.println(new String(dcipheredText));
        
           } catch (Exception e) {
        
           System.out.println(e);
        
         }
        
         }
        
   public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException,
              InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        
         Demo d = new Demo();
        
         byte b[] = d.encrypt("this is my password");
        
         d.decrypt(b);
        
         }
        
        }

Output : Ä°4k²Â bš_á ÔèR·ã«êæ?³Ъӌ

this is my password

No comments: