Created
November 5, 2016 18:01
-
-
Save NikhilAshodariya/e4de9004167176944f5d61cc2d631a08 to your computer and use it in GitHub Desktop.
This is AES 128 bit This program has a static methods encrypt and decrypt with key manual configured by developer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.codewithnikhil; | |
| import java.security.*; | |
| import java.security.spec.InvalidKeySpecException; | |
| import javax.crypto.Cipher; | |
| import javax.crypto.spec.SecretKeySpec; | |
| import sun.misc.*; | |
| public class Cryptographic { | |
| private static final String ALGORITHM = "AES"; | |
| private static final byte[] keyValue | |
| = new byte[] | |
| { | |
| 'N', 'i', 'k', 'h', 'i', 'l', 'a', 's', 'h', 'a', 'a', 'a', 'k', 'a', 's', 'h'/*this should be 16 character*/ | |
| }; | |
| public String encrypt(String value) throws Exception { | |
| Key key = generateKey(); | |
| Cipher c = Cipher.getInstance(ALGORITHM); | |
| c.init(Cipher.ENCRYPT_MODE, key); | |
| byte[] enc = c.doFinal(value.getBytes()); | |
| String encrypted = new BASE64Encoder().encode(enc); | |
| return encrypted; | |
| } | |
| public String decrypt(String encrypted) throws Exception { | |
| Key key = generateKey(); | |
| Cipher c = Cipher.getInstance(ALGORITHM); | |
| c.init(Cipher.DECRYPT_MODE, key); | |
| byte[] decorded = new BASE64Decoder().decodeBuffer(encrypted); | |
| byte[] dec = c.doFinal(decorded); | |
| String decrypted = new String(dec); | |
| return decrypted; | |
| } | |
| private Key generateKey() throws Exception { | |
| Key key = new SecretKeySpec(keyValue, ALGORITHM); | |
| return key; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment