Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement