Skip to content

Instantly share code, notes, and snippets.

@yccheok
Created April 11, 2015 15:23
Show Gist options
  • Save yccheok/e43aa336894dbf5106df to your computer and use it in GitHub Desktop.
Save yccheok/e43aa336894dbf5106df to your computer and use it in GitHub Desktop.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encryptiontest;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionTest {
private static final SecureRandom random = new SecureRandom();
public static String nextSessionId() {
return new BigInteger(130, random).toString(63);
}
public static void main(String[] args) throws UnsupportedEncodingException, GeneralSecurityException, Exception {
while(true) {
String key = nextSessionId();
String source = nextSessionId();
String result = encrypt(getKey(key), source);
System.out.println("source = " + source);
System.out.println("key = " + key);
System.out.println("result = " + result);
result = decrypt(getKey(key), result);
if (result.equals(source)) {
} else {
throw new Exception("Fail");
}
}
}
private static String encrypt(byte[] key, String value) throws GeneralSecurityException {
// Argument validation.
if (key.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
// Setup AES tool.
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// Do the job with AES tool.
byte[] original = value.getBytes(Charset.forName("UTF-8"));
byte[] binary = cipher.doFinal(original);
return Base64.getEncoder().encodeToString(binary);
}
private static String decrypt(byte[] key, String encrypted) throws GeneralSecurityException {
// Argument validation.
if (key.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
// Setup AES tool.
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// Do the job with AES tool.
byte[] binary = Base64.getDecoder().decode(encrypted);
byte[] original = cipher.doFinal(binary);
return new String(original, Charset.forName("UTF-8"));
}
private static byte[] getKey(String string) throws UnsupportedEncodingException, NoSuchAlgorithmException {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] key = sha.digest(string.getBytes("UTF-8"));
key = Arrays.copyOf(key, 16);
return key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment