Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.*;
- import java.security.*;
- import java.util.*;
- import javax.crypto.*;
- import javax.crypto.spec.*;
- public class Test {
- private static Key key;
- public static void main(String... args) {
- key = getKey("1234567890$");
- byte[] encrypted = encrypt("test");
- String str = new String(encrypted);
- System.out.println("encrypt: "+str);
- System.out.println("decrypt arr: "+decrypt(encrypted));
- System.out.println("decrypt str: "+decrypt(stringFromBytes(toHex(str))));
- }
- public static byte[] stringFromBytes(String s) {
- byte[] byteArray = new byte[s.length()/2];
- String[] strBytes = new String[s.length()/2];
- int k = 0;
- for (int i = 0; i < s.length(); i=i+2) {
- int j = i+2;
- strBytes[k] = s.substring(i,j);
- byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
- k++;
- }
- return byteArray;
- }
- private static String toHex(String s) {
- return String.format("%2x", new BigInteger(1, s.getBytes()));
- }
- private static String decrypt(byte[] enc) {
- try {
- Cipher cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.DECRYPT_MODE, key);
- return new String(cipher.doFinal(enc));
- } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {}
- return null;
- }
- private static byte[] encrypt(String text) {
- try {
- Cipher cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.ENCRYPT_MODE, key);
- return cipher.doFinal(text.getBytes());
- } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {}
- return null;
- }
- private static Key getKey(String pass) {
- if (pass != null && !pass.isEmpty())
- try {
- MessageDigest sha = MessageDigest.getInstance("SHA-1");
- byte[] key = pass.getBytes();
- key = sha.digest(key);
- key = Arrays.copyOf(key, 16);
- return new SecretKeySpec(key, "AES");
- } catch (NoSuchAlgorithmException e) {}
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement