Java Tutorial/Security/Advanced Encryption Standard

Материал из Java эксперт
Перейти к: навигация, поиск

AES Key generator

import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128);
    Key keyToBeWrapped = generator.generateKey();
    System.out.println("input    : " + new String(keyToBeWrapped.getEncoded()));
    Cipher cipher = Cipher.getInstance("AESWrap", "BC");
    KeyGenerator KeyGen = KeyGenerator.getInstance("AES", "BC");
    KeyGen.init(256);
    Key wrapKey = KeyGen.generateKey();
    cipher.init(Cipher.WRAP_MODE, wrapKey);
    byte[] wrappedKey = cipher.wrap(keyToBeWrapped);
    System.out.println("wrapped : " + new String(wrappedKey));
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
    System.out.println("unwrapped: " + new String(key.getEncoded()));
  }
}





AES wraps RSA

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
    SecureRandom random = new SecureRandom();
    KeyPairGenerator fact = KeyPairGenerator.getInstance("RSA", "BC");
    fact.initialize(1024, random);
    KeyPair keyPair = fact.generateKeyPair();
    Key wrapKey = createKeyForAES(256, random);
    cipher.init(Cipher.WRAP_MODE, wrapKey);
    byte[] wrappedKey = cipher.wrap(keyPair.getPrivate());
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    Key key = cipher.unwrap(wrappedKey, "RSA", Cipher.PRIVATE_KEY);
    System.out.println(keyPair.getPrivate().equals(key));
  }
  public static SecretKey createKeyForAES(int bitLength, SecureRandom random)
      throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128, random);
    return generator.generateKey();
  }
}





Tampered message, encryption with digest, AES in CTR mode

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES(1, random);
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "12345678";
    MessageDigest hash = MessageDigest.getInstance("SHA-1", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + hash.getDigestLength())];
    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);
    hash.update(input.getBytes());
    ctLength += cipher.doFinal(hash.digest(), 0, hash.getDigestLength(), cipherText, ctLength);
    cipherText[9] ^= "0" ^ "9";
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - hash.getDigestLength();
    hash.update(plainText, 0, messageLength);
    byte[] messageHash = new byte[hash.getDigestLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);
    System.out.println("plain : " + new String(plainText) + " verified: "
        + MessageDigest.isEqual(hash.digest(), messageHash));
  }
  public static SecretKey createKeyForAES(int bitLength, SecureRandom random)
      throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128, random);
    return generator.generateKey();
  }
  public static IvParameterSpec createCtrIvForAES(int messageNumber, SecureRandom random) {
    byte[] ivBytes = new byte[16];
    random.nextBytes(ivBytes);
    ivBytes[0] = 1;
    ivBytes[1] = 2;
    ivBytes[2] = 3;
    ivBytes[3] = 4;
    for (int i = 0; i != 7; i++) {
      ivBytes[8 + i] = 0;
    }
    ivBytes[15] = 1;
    return new IvParameterSpec(ivBytes);
  }
}





Tampered message, plain encryption, AES in CTR mode

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES(1, random);
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "input1234567";
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] cipherText = cipher.doFinal(input.getBytes());
    cipherText[9] ^= "0" ^ "9";
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] plainText = cipher.doFinal(cipherText);
    System.out.println("plain : " + new String(plainText));
  }
  public static SecretKey createKeyForAES(int bitLength, SecureRandom random)
      throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128, random);
    return generator.generateKey();
  }
  public static IvParameterSpec createCtrIvForAES(int messageNumber, SecureRandom random) {
    byte[] ivBytes = new byte[16];
    random.nextBytes(ivBytes);
    ivBytes[0] = 1;
    ivBytes[1] = 2;
    ivBytes[2] = 3;
    ivBytes[3] = 4;
    for (int i = 0; i != 7; i++) {
      ivBytes[8 + i] = 0;
    }
    ivBytes[15] = 1;
    return new IvParameterSpec(ivBytes);
  }
}





Tampered message with HMac, encryption with AES in CTR mode

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES();
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "12345678";
    Mac hMac = Mac.getInstance("HmacSHA1", "BC");
    Key hMacKey = new SecretKeySpec(key.getEncoded(), "HmacSHA1");
    System.out.println("input : " + input);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + hMac.getMacLength())];
    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);
    hMac.init(hMacKey);
    hMac.update(input.getBytes());
    ctLength += cipher.doFinal(hMac.doFinal(), 0, hMac.getMacLength(), cipherText, ctLength);
    cipherText[9] ^= "0" ^ "9";
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - hMac.getMacLength();
    hMac.init(hMacKey);
    hMac.update(plainText, 0, messageLength);
    byte[] messageHash = new byte[hMac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);
    System.out.println("plain : " + new String(plainText) + " verified: "
        + MessageDigest.isEqual(hMac.doFinal(), messageHash));
  }
  public static SecretKey createKeyForAES(int bitLength, SecureRandom random)
      throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128, random);
    return generator.generateKey();
  }
  public static IvParameterSpec createCtrIvForAES() {
    return new IvParameterSpec("1234567812345678".getBytes());
  }
}





using the KeyGenerator class and showing how to create a SecretKeySpec from an encoded key.

import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MainClass {
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "input".getBytes();
    byte[] ivBytes = "1234567812345678".getBytes();
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128);
    Key encryptionKey = generator.generateKey();
    System.out.println("key : " + new String(encryptionKey.getEncoded()));
    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes));
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    Key decryptionKey = new SecretKeySpec(encryptionKey.getEncoded(), encryptionKey.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(ivBytes));
    byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
    int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    System.out.println("plain : " + new String(plainText));
  }
}