· 7 years ago · Apr 26, 2018, 08:18 AM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6
7
8
9import java.security.Key;
10
11import java.security.KeyPair;
12
13import java.security.KeyPairGenerator;
14
15import java.security.Security;
16
17import java.security.SecureRandom;
18
19import javax.crypto.Cipher;
20
21
22import java.security.InvalidKeyException;
23import java.security.NoSuchAlgorithmException;
24import java.security.spec.InvalidKeySpecException;
25import javax.crypto.BadPaddingException;
26import javax.crypto.IllegalBlockSizeException;
27import javax.crypto.NoSuchPaddingException;
28import javax.crypto.SecretKey;
29import javax.crypto.SecretKeyFactory;
30import javax.crypto.ShortBufferException;
31import javax.crypto.spec.PBEKeySpec;
32import javax.crypto.spec.SecretKeySpec;
33
34import javax.rmi.CORBA.Util;
35
36
37/**
38 *
39 * @author student
40 */
41public class JavaApplication9 {
42
43 /**
44 * @param args the command line arguments
45 * @throws java.security.NoSuchAlgorithmException
46 */
47 public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
48
49 Cipher myAES;
50 myAES = Cipher.getInstance("AES/ECB/NoPadding");
51 SecureRandom myPRNG = new SecureRandom();
52 byte[] keyBytes = new byte[16];
53 SecretKeySpec myKey = new SecretKeySpec(keyBytes, "AES");
54 myAES.init(Cipher.ENCRYPT_MODE, myKey);
55 myAES.init(Cipher.DECRYPT_MODE, myKey);
56 byte[] plaintext = new byte[16];
57 byte[] ciphertext = new byte[16];
58 int cLength = myAES.update(plaintext, 0, plaintext.length, ciphertext, 0);
59 += myAES.doFinal(ciphertext, cLength);
60
61
62 System.out.println("plaintext: " + javax.xml.bind.DatatypeConverter.printHexBinary(plaintext));
63 System.out.println("ciphertext: " + javax.xml.bind.DatatypeConverter.printHexBinary(ciphertext));
64
65 myAES.init(Cipher.DECRYPT_MODE, myKey);
66 decryption byte[] dec_plaintext = new byte[16];
67 cLength = myAES.update(ciphertext, 0, ciphertext.length, dec_plaintext, 0);
68
69 += myAES.doFinal(dec_plaintext, cLength);
70 System.out.println("decrypted: " + javax.xml.bind.DatatypeConverter.printHexBinary(dec_plaintext));
71
72 char[] password = "short_password".toCharArray();
73 byte[] salt = new byte[16];
74 int iteration_count = 10000;
75 int key_size = 128;
76 myPRNG.nextBytes(salt);
77
78 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
79 PBEKeySpec pbekSpec = new PBEKeySpec(password, salt, iteration_count, key_size);
80 SecretKey myAESPBKey = new SecretKeySpec( keyFactory.generateSecret(pbekSpec).getEncoded(), "AES");
81 System.out.println("AES key: " +javax.xml.bind.DatatypeConverter.printHexBinary(myAESPBKey.getEncoded()));
82
83 }
84
85}