Java/Security/Key Generator
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Asymmetric Key Maker
- 2 Generate a 1024-bit RSA key pair
- 3 Generate a 576-bit DH key pair
- 4 Generate a key for the HMAC-SHA1 keyed-hashing algorithm
- 5 Generate DSA key pair
- 6 Generating a Public/Private Key Pair
- 7 Generating a Symmetric Key
- 8 Get the bytes of the public and private keys
- 9 Getting the Bytes of a Generated Key Pair
- 10 Key Generator Mac
- 11 KeyPair Generator For Private Key
- 12 KeyPair Generator For Public Key
- 13 The bytes can be converted back to public and private key objects
- 14 Using the KeyGenerator class and showing how to create a SecretKeySpec from an encoded key
- 15 Wrap And Unwrap Key
Asymmetric Key Maker
import java.security.KeyPair;
import java.security.KeyPairGenerator;
public class Main {
public static void main(String[] args) throws Exception {
String algorithm = "";
KeyPair keyPair = KeyPairGenerator.getInstance(algorithm).generateKeyPair();
System.out.println(keyPair.getPublic());
System.out.println(keyPair.getPrivate());
}
}
Generate a 1024-bit RSA key pair
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Main {
public static void main(String[] argv) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
}
}
Generate a 576-bit DH key pair
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Main {
public static void main(String[] argv) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
keyGen.initialize(576);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
}
}
Generate a key for the HMAC-SHA1 keyed-hashing algorithm
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Main {
public static void main(String[] argv) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
SecretKey key = keyGen.generateKey();
// Generate a key for the HMAC-SHA1 keyed-hashing algorithm
keyGen = KeyGenerator.getInstance("HmacSHA1");
key = keyGen.generateKey();
}
}
Generate DSA key pair
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
public class MainClass {
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(1024, new SecureRandom());
KeyPair dsaKeyPair = kpg.generateKeyPair();
}
}
Generating a Public/Private Key Pair
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Main {
public static void main(String[] argv) throws Exception {
// Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
System.out.println(privateKey);
PublicKey publicKey = keypair.getPublic();
System.out.println(publicKey);
}
}
Generating a Symmetric Key
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Main {
public static void main(String[] argv) throws Exception {
// Generate a DES key
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
SecretKey key = keyGen.generateKey();
// Generate a Blowfish key
keyGen = KeyGenerator.getInstance("Blowfish");
key = keyGen.generateKey();
// Generate a triple DES key
keyGen = KeyGenerator.getInstance("DESede");
key = keyGen.generateKey();
}
}
Get the bytes of the public and private keys
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Main {
public static void main(String[] argv) throws Exception {
String algorithm = "DSA"; // or RSA, DH, etc.
// Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(1024);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
}
}
Getting the Bytes of a Generated Key Pair
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Main {
public static void main(String[] argv) throws Exception {
String algorithm = "DSA"; // or RSA, DH, etc.
// Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(1024);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
}
}
Key Generator Mac
import java.security.Security;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
public class MainClass {
public static void main(String args[]) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String inputString = "www.jexp.ru";
KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
SecretKey secretKey = keyGen.generateKey();
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
byte[] byteData = inputString.getBytes("UTF8");
byte[] macBytes = mac.doFinal(byteData);
String macAsString = new sun.misc.BASE64Encoder().encode(macBytes);
System.out.println("Authentication code is: " + macAsString);
}
}
KeyPair Generator For Private Key
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Security;
public class MainClass {
public KeyPair generateKeyPair(long seed)throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
rng.setSeed(seed);
keyGenerator.initialize(1024, rng);
return (keyGenerator.generateKeyPair());
}
public static void main(String args[]) throws Exception {
MainClass kpge = new MainClass();
KeyPair kp = kpge.generateKeyPair(999);
System.out.println("\n-- Private Key ----");
PrivateKey priKey = kp.getPrivate();
System.out.println(" Algorithm=" + priKey.getAlgorithm());
System.out.println(" Encoded=" + priKey.getEncoded());
System.out.println(" Format=" + priKey.getFormat());
}
}
KeyPair Generator For Public Key
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
public class MainClass {
public KeyPair generateKeyPair(long seed)throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
rng.setSeed(seed);
keyGenerator.initialize(1024, rng);
return (keyGenerator.generateKeyPair());
}
public static void main(String args[]) throws Exception {
MainClass kpge = new MainClass();
KeyPair kp = kpge.generateKeyPair(999);
System.out.println("-- Public Key ----");
PublicKey pubKey = kp.getPublic();
System.out.println(" Algorithm=" + pubKey.getAlgorithm());
System.out.println(" Encoded=" + pubKey.getEncoded());
System.out.println(" Format=" + pubKey.getFormat());
}
}
The bytes can be converted back to public and private key objects
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Main {
public static void main(String[] argv) throws Exception {
String algorithm = "DSA"; // or RSA, DH, etc.
// Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(1024);
KeyPair keypair = keyGen.genKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);
// The orginal and new keys are the same
boolean same = privateKey.equals(privateKey2);
same = publicKey.equals(publicKey2);
}
}
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;
/**
* Basic example using the KeyGenerator class and showing how to create a
* SecretKeySpec from an encoded key.
*/
public class MainClass {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] input = "www.jexp.ru".getBytes();
byte[] ivBytes = new byte[] { 0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01 };
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
generator.init(192);
Key encryptionKey = generator.generateKey();
System.out.println("key : " + Utils.toHex(encryptionKey.getEncoded()));
System.out.println("input : " + new String(input));
// encryption pass
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);
// decryption pass
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) + " bytes: " + ptLength);
}
}
class Utils
{
private static String digits = "0123456789abcdef";
/**
* Return length many bytes of the passed in byte array as a hex string.
*
* @param data the bytes to be converted.
* @param length the number of bytes in the data block to be converted.
* @return a hex representation of length bytes of data.
*/
public static String toHex(byte[] data, int length)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i != length; i++)
{
int v = data[i] & 0xff;
buf.append(digits.charAt(v >> 4));
buf.append(digits.charAt(v & 0xf));
}
return buf.toString();
}
/**
* Return the passed in byte array as a hex string.
*
* @param data the bytes to be converted.
* @return a hex representation of data.
*/
public static String toHex(byte[] data)
{
return toHex(data, data.length);
}
}
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()));
}
}