Java/Security/Key Generator
Содержание
- 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
<source lang="java">
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()); }
}
</source>
Generate a 1024-bit RSA key pair
<source lang="java">
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(); }
}
</source>
Generate a 576-bit DH key pair
<source lang="java">
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(); }
}
</source>
Generate a key for the HMAC-SHA1 keyed-hashing algorithm
<source lang="java">
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(); }
}
</source>
Generate DSA key pair
<source lang="java">
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(); }
}
</source>
Generating a Public/Private Key Pair
<source lang="java">
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); }
}
</source>
Generating a Symmetric Key
<source lang="java">
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(); }
}
</source>
Get the bytes of the public and private keys
<source lang="java">
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(); }
}
</source>
Getting the Bytes of a Generated Key Pair
<source lang="java">
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(); }
}
</source>
Key Generator Mac
<source lang="java">
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); }
}
</source>
KeyPair Generator For Private Key
<source lang="java">
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()); }
}
</source>
KeyPair Generator For Public Key
<source lang="java">
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()); }
}
</source>
The bytes can be converted back to public and private key objects
<source lang="java">
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); }
}
</source>
Using the KeyGenerator class and showing how to create a SecretKeySpec from an encoded key
<source lang="java">
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); }
}
</source>
Wrap And Unwrap Key
<source lang="java">
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())); }
}
</source>