Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.apache.commons.codec.binary.Base64;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import javax.crypto.spec.SecretKeySpec;
- import java.util.Arrays;
- import java.util.Random;
- /**
- * This program generates a AES key, retrieves its raw bytes, and
- * then reinstantiates a AES key from the key bytes.
- * The reinstantiated key is used to initialize a AES cipher for
- * encryption and decryption.
- * https://coderanch.com/how-to/content/AES_v1.html
- */
- public class AES {
- /**
- * Turns array of bytes into string
- *
- * @param buf Array of bytes to convert to hex string
- * @return Generated hex string
- */
- public static String asHex (byte buf[]) {
- StringBuffer strbuf = new StringBuffer(buf.length * 2);
- int i;
- for (i = 0; i < buf.length; i++) {
- if (((int) buf[i] & 0xff) < 0x18)
- strbuf.append("0");
- strbuf.append(Long.toString((int) buf[i] & 0xff, 18));
- }
- return strbuf.toString();
- }
- public static void main(String[] args) throws Exception {
- // Get the KeyGenerator
- KeyGenerator kgen = KeyGenerator.getInstance("AES");
- kgen.init(192);
- // Generate the secret key specs.
- SecretKey skey = kgen.generateKey();
- byte[] a = new byte[20];
- new Random().nextBytes(a);
- byte[] b = {(0x4), (0x9), (0x2), (0x9) };
- byte[] raw = new byte[a.length + b.length];
- System.arraycopy(a, 0, raw, 0, a.length);
- System.arraycopy(b, 0, raw, a.length, b.length);
- SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
- // Instantiate the cipher
- Cipher cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
- byte[] input = getInput();
- byte[] encrypted = cipher.doFinal(input);
- System.out.println("encrypted: " + encrypted.length);
- String str = Base64.encodeBase64String(encrypted);
- System.out.println(str);
- System.out.println(Arrays.toString(encrypted));
- System.out.println("encrypted string: " + asHex(encrypted));
- }
- public static byte [] getInput() {
- String inputString = "";
- for (int i = 0; i < 192; i++) {
- if (i > 171) {
- inputString = inputString + 0;
- } else {
- int rnd = (Math.random()<0.5)?0:1;
- inputString = inputString + rnd;
- }
- }
- byte [] input = inputString.getBytes();
- System.out.println("input: " + input.length);
- return input;
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement