Encryption and Decryption using Symmetric Keys : Key Generator « Security « Java Tutorial






import java.security.InvalidKeyException;
import java.security.Key;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;

public class Main {
  static String algorithm = "DESede";
  static Key key = KeyGenerator.getInstance(algorithm).generateKey();
  static Cipher cipher = Cipher.getInstance(algorithm);

  public static void main(String[] args) throws Exception {
    byte[] encryptionBytes = encrypt("input");
    System.out.println("Recovered: " + decrypt(encryptionBytes));
  }

  private static byte[] encrypt(String input) throws InvalidKeyException, BadPaddingException,
      IllegalBlockSizeException {
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] inputBytes = input.getBytes();
    return cipher.doFinal(inputBytes);
  }

  private static String decrypt(byte[] encryptionBytes) throws InvalidKeyException,
      BadPaddingException, IllegalBlockSizeException {
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
    String recovered = new String(recoveredBytes);
    return recovered;
  }
}








36.21.Key Generator
36.21.1.Key Generator Demo
36.21.2.Generating a Symmetric Key
36.21.3.Getting the Bytes of a Generated Symmetric Key
36.21.4.Generate a key for the HMAC-SHA1 keyed-hashing algorithm
36.21.5.Encryption and Decryption using Symmetric Keys
36.21.6.Get the bytes of the public and private keys
36.21.7.Get the formats of the encoded bytes