Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.security.GeneralSecurityException;
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;
- import util.B64;
- public class Crypt {
- public static void main(String[] args) throws Exception {
- // Receive Key
- String KEY = "57238004e784498bbc2f8bf984565090";
- // Message
- String MSG = "HELLO WORLD";
- // Example
- String encrypt = encrypt(MSG, KEY);
- String decrypt = decrypt(B64.dec(encrypt), B64.enc(KEY));
- }
- public static String encrypt(String msg, String keyHexString) throws GeneralSecurityException {
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
- SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(keyHexString), "AES");
- cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
- byte[] encrypted = cipher.doFinal(msg.getBytes());
- return new String(B64.enc(byteArrayToHexString(encrypted)));
- }
- public static String decrypt(String msg64String, String keyHex64String) throws Exception {
- Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
- SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(B64.dec(keyHex64String)), "AES");
- cipher.init(Cipher.DECRYPT_MODE, sks, cipher.getParameters());
- byte[] encrypted = cipher.doFinal(hexStringToByteArray(msg64String));
- return new String(encrypted);
- }
- public static byte[] hexStringToByteArray(String s) {
- byte[] b = new byte[s.length() / 2];
- for (int i = 0; i < b.length; i++) {
- int index = i * 2;
- int v = Integer.parseInt(s.substring(index, index + 2), 16);
- b[i] = (byte) v;
- }
- return b;
- }
- public static String byteArrayToHexString(byte[] b) {
- StringBuilder sb = new StringBuilder(b.length * 2);
- for (int i = 0; i < b.length; i++) {
- int v = b[i] & 0xff;
- if (v < 16) {
- sb.append('0');
- }
- sb.append(Integer.toHexString(v));
- }
- return sb.toString().toUpperCase();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement