Advertisement
Guest User

AESTest

a guest
Apr 12th, 2014
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import javax.crypto.Cipher;
  2. import javax.crypto.SecretKey;
  3. import javax.crypto.SecretKeyFactory;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.PBEKeySpec;
  6. import javax.crypto.spec.SecretKeySpec;
  7. import java.security.AlgorithmParameters;
  8. import java.security.spec.KeySpec;
  9.  
  10. public class AESTest {
  11.  
  12.     public static void main(String[] args) throws Exception {
  13.  
  14.         String textToEncrypt = "SecretPhrase";
  15.         // hexadecimal of "SecretPhrase" generated by crypto
  16.         String hexGeneratedInCrypto = "a39e724d866461b97d0982d6ef72e567";
  17.  
  18.         byte[] salt = null; // I don't know tha salt because in crypto it's calculated automatically
  19.         char[] password = "mypassword".toCharArray();
  20.  
  21.         SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
  22.         KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
  23.         SecretKey tmp = factory.generateSecret(spec);
  24.         SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
  25.  
  26.         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  27.         cipher.init(Cipher.ENCRYPT_MODE, secret);
  28.         AlgorithmParameters params = cipher.getParameters();
  29.         byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
  30.         byte[] encrypted = cipher.doFinal(textToEncrypt.getBytes("UTF-8"));
  31.  
  32.         // I need hex(encrypted) == hexGeneratedInCrypto
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement