Wrap And Unwrap Key : Key Generator « Security « Java






Wrap And Unwrap Key

   
import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

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()));

    // create a wrapper and do the wrapping
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
    KeyGenerator keyGen = KeyGenerator.getInstance("AES", "BC");
    keyGen.init(256);
    Key wrapKey = keyGen.generateKey();
    cipher.init(Cipher.ENCRYPT_MODE, wrapKey);
    byte[] wrappedKey = cipher.doFinal(keyToBeWrapped.getEncoded());
    System.out.println("wrapped  : " + new String(wrappedKey));

    // unwrap the wrapped key
    cipher.init(Cipher.DECRYPT_MODE, wrapKey);
    Key key = new SecretKeySpec(cipher.doFinal(wrappedKey), "AES");
    System.out.println("unwrapped: " + new String(key.getEncoded()));
  }
}

           
         
    
    
  








WrapAndUnwrapKey.zip( 1,198 k)

Related examples in the same category

1.Using the KeyGenerator class and showing how to create a SecretKeySpec from an encoded key
2.Key Generator Mac
3.Generate DSA key pair
4.KeyPair Generator For Private Key
5.KeyPair Generator For Public Key
6.Generating a Public/Private Key Pair
7.Generate a 576-bit DH key pair
8.Generate a 1024-bit RSA key pair
9.Getting the Bytes of a Generated Key Pair
10.Get the bytes of the public and private keys
11.The bytes can be converted back to public and private key objects
12.Generate a key for the HMAC-SHA1 keyed-hashing algorithm
13.Asymmetric Key Maker
14.Generating a Symmetric Key
15.Xml dap Certs And Keys
16.Diffie-Hellman key exchange