下面列出了javax.crypto.KeyGenerator#getInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void wrapperPublicPriviteKeyTest(Provider p, String[] algorithms)
throws NoSuchAlgorithmException, InvalidKeyException,
NoSuchPaddingException, IllegalBlockSizeException,
InvalidAlgorithmParameterException {
for (String algo : algorithms) {
// Key pair generated
System.out.println("Generate key pair (algorithm: " + algo
+ ", provider: " + p.getName() + ")");
KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
kpg.initialize(512);
KeyPair kp = kpg.genKeyPair();
// key generated
String algoWrap = "DES";
KeyGenerator kg = KeyGenerator.getInstance(algoWrap, p);
Key key = kg.generateKey();
wrapTest(algo, algoWrap, key, kp.getPrivate(), Cipher.PRIVATE_KEY,
false);
wrapTest(algo, algoWrap, key, kp.getPublic(), Cipher.PUBLIC_KEY,
false);
}
}
/**
* 初始化密钥
* @param seed
* @return
* @throws Exception
*/
public static Key initSecretKey(String seed) throws Exception{
//返回生成指定算法的密钥 KeyGenerator
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORIHM);
//初始化此密钥生成器,使其具有确定的密钥大小
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(seed.getBytes());
keyGenerator.init(KEY_SITE,secureRandom);
//生成一个密钥
SecretKey secretKey = keyGenerator.generateKey();
//实例化DES 密钥规则
DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(secretKey.getEncoded());
//实例化密钥工厂
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORIHM);
//生成密钥
return secretKeyFactory.generateSecret(deSedeKeySpec);
}
/**
* 生成加密秘钥
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
// javax.crypto.BadPaddingException: Given final block not properly padded解决方案
// https://www.cnblogs.com/zempty/p/4318902.html - 用此法解决的
// https://www.cnblogs.com/digdeep/p/5580244.html - 留作参考吧
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
//AES 要求密钥长度为 128
kg.init(128, random);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
// 转换为AES专用密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
public void main(Provider provider) throws Exception {
if (provider.getService(
"KeyGenerator", "SunTlsRsaPremasterSecret") == null) {
System.out.println("Not supported by provider, skipping");
return;
}
KeyGenerator kg;
kg = KeyGenerator.getInstance("SunTlsRsaPremasterSecret", provider);
try {
kg.generateKey();
throw new Exception("no exception");
} catch (IllegalStateException e) {
System.out.println("OK: " + e);
}
int[] protocolVersions = {0x0300, 0x0301, 0x0302, 0x0400};
for (int clientVersion : protocolVersions) {
for (int serverVersion : protocolVersions) {
test(kg, clientVersion, serverVersion);
if (serverVersion >= clientVersion) {
break;
}
}
}
System.out.println("Done.");
}
public static SecretKey generateKey() {
try {
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(CRYPTO_AEAD_KEY_SIZE * 8);
return generator.generateKey();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
/**
* 解密函数
*
* @param src 加密过的二进制字符数组
* @param strKey 密钥
* @return
* @throws Exception
*/
public static String deCryptAndDecode(byte[] src, String strKey) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom(strKey.getBytes()));
SecretKey desKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, desKey);
byte[] cByte = cipher.doFinal(src);
return new String(cByte, "UTF-8");
}
public static void main(String[] args) throws Exception {
Provider provider = Security.getProvider("SunJCE");
if (provider == null) {
throw new RuntimeException("SunJCE provider not exist");
}
// generate no-padding cipher with secret key
Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider);
KeyGenerator kgen = KeyGenerator.getInstance("DES", provider);
SecretKey skey = kgen.generateKey();
// this is the improperly padded plaintext
c.init(Cipher.ENCRYPT_MODE, skey);
// encrypt plaintext
byte[] cipher = c.doFinal(PLAIN_TEXT);
AlgorithmParameters params = c.getParameters();
// generate cipher that enforces PKCS5 padding
c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider);
c.init(Cipher.DECRYPT_MODE, skey, params);
try {
c.doFinal(cipher);
throw new RuntimeException(
"ERROR: Expected BadPaddingException not thrown");
} catch (BadPaddingException expected) {
out.println("Expected BadPaddingException thrown");
}
}
public static SecretKey generateKey(String algo, int keySize) throws TechnicalConnectorException {
try {
if (keyGen == null) {
keyGen = KeyGenerator.getInstance(algo);
}
keyGen.init(keySize, new SecureRandom());
return keyGen.generateKey();
} catch (NoSuchAlgorithmException var3) {
throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var3, new Object[]{var3.getMessage()});
}
}
@BeforeClass
public static void setUpClass() throws Exception {
KeyGenerator aesGen = KeyGenerator.getInstance("AES");
aesGen.init(128, Utils.getRng());
encryptionKey = aesGen.generateKey();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, Utils.getRng());
macKey = macGen.generateKey();
}
/**
* AES解密
* @param encryptBytes 待解密的byte[]
* @param decryptKey 解密密钥
* @return 解密后的String
* @throws Exception
*/
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(decryptKey.getBytes()));
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
public void main(Provider provider) throws Exception {
if (provider.getService(
"KeyGenerator", "SunTlsRsaPremasterSecret") == null) {
System.out.println("Not supported by provider, skipping");
return;
}
KeyGenerator kg;
kg = KeyGenerator.getInstance("SunTlsRsaPremasterSecret", provider);
try {
kg.generateKey();
throw new Exception("no exception");
} catch (IllegalStateException e) {
System.out.println("OK: " + e);
}
int[] protocolVersions = {0x0300, 0x0301, 0x0302, 0x0400};
for (int clientVersion : protocolVersions) {
for (int serverVersion : protocolVersions) {
test(kg, clientVersion, serverVersion);
if (serverVersion >= clientVersion) {
break;
}
}
}
System.out.println("Done.");
}
private byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = null;
if (android.os.Build.VERSION.SDK_INT >= JELLY_BEAN_4_2) {
sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
} else {
sr = SecureRandom.getInstance("SHA1PRNG");
}
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
/**
* 初始化HmacSHA1密钥
*
* @return
*
* @throws Exception
*/
public static byte[] initHmacSHAKey() throws NoSuchAlgorithmException {
// 初始化KeyGenerator
KeyGenerator keyGenerator = KeyGenerator.getInstance("HMacTiger");
// 产生秘密密钥
SecretKey secretKey = keyGenerator.generateKey();
// 获得密钥
return secretKey.getEncoded();
}
private void wrapperBlowfishKeyTest() throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException {
// how many kinds of padding mode
int padKinds;
// Keysize should be multiple of 8 bytes.
int KeyCutter = 8;
int kSize = BLOWFISH_MIN_KEYSIZE;
String algorithm = "Blowfish";
int maxAllowKeyLength = Cipher.getMaxAllowedKeyLength(algorithm);
boolean unLimitPolicy = maxAllowKeyLength == Integer.MAX_VALUE;
SecretKey key = null;
while (kSize <= BLOWFISH_MAX_KEYSIZE) {
for (String mode : MODEL_AR) {
// PKCS5padding is meaningful only for ECB, CBC, PCBC
if (mode.equalsIgnoreCase(MODEL_AR[0])
|| mode.equalsIgnoreCase(MODEL_AR[1])
|| mode.equalsIgnoreCase(MODEL_AR[2])) {
padKinds = PADDING_AR.length;
} else {
padKinds = 1;
}
// Initialization
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
for (int k = 0; k < padKinds; k++) {
String transformation = algorithm + "/" + mode + "/"
+ PADDING_AR[k];
if (NOPADDING.equals(PADDING_AR[k]) && kSize % 64 != 0) {
out.println(transformation
+ " will not run if input length not multiple"
+ " of 8 bytes when padding is " + NOPADDING);
continue;
}
kg.init(kSize);
key = kg.generateKey();
// only run the tests on longer key lengths if unlimited
// version of JCE jurisdiction policy files are installed
if (!unLimitPolicy && kSize > LINIMITED_KEYSIZE) {
out.println("keyStrength > 128 within " + algorithm
+ " will not run under global policy");
} else {
wrapTest(transformation, transformation, key, key,
Cipher.SECRET_KEY, false);
}
}
}
if (kSize <= LINIMITED_KEYSIZE) {
KeyCutter = 8;
} else {
KeyCutter = 48;
}
kSize += KeyCutter;
}
}
/**
* Generates a new AES key and stores it under the { @code KEY_ALIAS_AES } in the
* Android Keystore.
*/
@SuppressWarnings("StatementWithEmptyBody")
private void generateAesKey() {
try {
// The KeyGenerator is an engine class for creating symmetric keys utilizing the
// algorithm it was initialized with.
KeyGenerator keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER);
// Create a new instance of the KeyGenParameterSpec.Builder, hand over
// the key alias and the different purposes for which you want to use the key.
// Keep in mind that you can only use the key for the operations you have specified
// here - once the key is created it can't be changed.
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
KEY_ALIAS_AES,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
// Define the basic encryption parameters for the key. The set configuration
// matches the AES_DEFAULT_TRANSFORMATION constant.
builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setKeySize(256)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
if (mRadioUserAuthentication.isChecked()) {
// Create a key which requires the user to be authenticated during
// the last 30 seconds. Could also be 30 seconds or even 5 minutes -
// choose whatever fits your security guidelines best.
// Before continuing, check if the user has set up a secure lockscreen -
// if not, prompt the user to set one up ;-)
if (!hasSetupSecureLockscreen()) return;
builder.setUserAuthenticationRequired(true)
.setUserAuthenticationValidityDurationSeconds(15);
} else if (mRadioUserFingerprint.isChecked()) {
// Create a key which needs fingerprint authentication every time.
// Before continuing, check if the device supports fingerprint
// authentication and if the user has at least enrolled one fingerprint -
// if not, prompt the user to enroll one ;-)
if (!hasSetupFingerprint()) return;
builder.setUserAuthenticationRequired(true);
} else {
// Create a key which does not need any user authentication.
// Nothing more to add here!
}
// Initialize the KeyGenerator with the KeyGenParameterSpec which will be created by
// the KeyGenParameterSpec.Builder .
keyGenerator.init(builder.build());
// Finally, generate the key...
keyGenerator.generateKey();
// ...and show a TextView with a confirmation text.
showSuccessTextView();
} catch (NoSuchAlgorithmException | NoSuchProviderException
| InvalidAlgorithmParameterException e) {
throw new RuntimeException("Failed to create a symmetric key", e);
}
}
public static void main(String[] args) throws Exception {
Provider provider = Security.getProvider("SunJCE");
InputStream in = new FileInputStream(new File(BASE, "masterdata.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int n = 0;
int lineNumber = 0;
String algorithm = null;
byte[] premaster = null;
byte[] clientRandom = null;
byte[] serverRandom = null;
int protoMajor = 0;
int protoMinor = 0;
int preMajor = 0;
int preMinor = 0;
byte[] master = null;
while (true) {
String line = reader.readLine();
lineNumber++;
if (line == null) {
break;
}
if (line.startsWith("m-") == false) {
continue;
}
String data = line.substring(PREFIX_LENGTH);
if (line.startsWith("m-algorithm:")) {
algorithm = data;
} else if (line.startsWith("m-premaster:")) {
premaster = parse(data);
} else if (line.startsWith("m-crandom:")) {
clientRandom = parse(data);
} else if (line.startsWith("m-srandom:")) {
serverRandom = parse(data);
} else if (line.startsWith("m-protomajor:")) {
protoMajor = Integer.parseInt(data);
} else if (line.startsWith("m-protominor:")) {
protoMinor = Integer.parseInt(data);
} else if (line.startsWith("m-premajor:")) {
preMajor = Integer.parseInt(data);
} else if (line.startsWith("m-preminor:")) {
preMinor = Integer.parseInt(data);
} else if (line.startsWith("m-master:")) {
master = parse(data);
System.out.print(".");
n++;
KeyGenerator kg =
KeyGenerator.getInstance("SunTlsMasterSecret", provider);
SecretKey premasterKey =
new SecretKeySpec(premaster, algorithm);
TlsMasterSecretParameterSpec spec =
new TlsMasterSecretParameterSpec(premasterKey, protoMajor,
protoMinor, clientRandom, serverRandom,
null, -1, -1);
kg.init(spec);
TlsMasterSecret key = (TlsMasterSecret)kg.generateKey();
byte[] enc = key.getEncoded();
if (Arrays.equals(master, enc) == false) {
throw new Exception("mismatch line: " + lineNumber);
}
if ((preMajor != key.getMajorVersion()) ||
(preMinor != key.getMinorVersion())) {
throw new Exception("version mismatch line: " + lineNumber);
}
} else {
throw new Exception("Unknown line: " + line);
}
}
if (n == 0) {
throw new Exception("no tests");
}
in.close();
System.out.println();
System.out.println("OK: " + n + " tests");
}
private static void runTest(Provider p, String algo, String mo, String pad,
ReadModel whichRead) throws GeneralSecurityException, IOException {
// Do initialization
byte[] plainText = TestUtilities.generateBytes(TEXT_LENGTH);
byte[] iv = TestUtilities.generateBytes(IV_LENGTH);
AlgorithmParameterSpec aps = new IvParameterSpec(iv);
try {
KeyGenerator kg = KeyGenerator.getInstance(algo, p);
out.println(algo + "/" + mo + "/" + pad + "/" + whichRead);
SecretKey key = kg.generateKey();
Cipher ci1 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
throw new RuntimeException(
"NoSuchAlgorithmException not throw when mode"
+ " is CFB72 or OFB20");
}
Cipher ci2 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
if ("ECB".equalsIgnoreCase(mo)) {
ci1.init(Cipher.ENCRYPT_MODE, key);
ci2.init(Cipher.DECRYPT_MODE, key);
} else {
ci1.init(Cipher.ENCRYPT_MODE, key, aps);
ci2.init(Cipher.DECRYPT_MODE, key, aps);
}
ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
try (CipherInputStream cInput
= new CipherInputStream(
new ByteArrayInputStream(plainText), ci1);
CipherOutputStream ciOutput
= new CipherOutputStream(baOutput, ci2);) {
// Read from the input and write to the output using 2 types
// of buffering : byte[] and int
whichRead.read(cInput, ciOutput, ci1, plainText.length);
}
// Verify input and output are same.
if (!Arrays.equals(plainText, baOutput.toByteArray())) {
throw new RuntimeException("Test failed due to compare fail ");
}
} catch (NoSuchAlgorithmException nsaEx) {
if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
out.println("NoSuchAlgorithmException is expected for CFB72 and OFB20");
} else {
throw new RuntimeException("Unexpected exception testing: "
+ algo + "/" + mo + "/" + pad + "/" + whichRead, nsaEx);
}
}
}
public KeyGenerator createKeyGenerator(String algorithm)
throws NoSuchAlgorithmException, NoSuchProviderException
{
return KeyGenerator.getInstance(algorithm, providerName);
}
private void runTest(String mo, String pad, int keySize)
throws NoSuchPaddingException, BadPaddingException,
ShortBufferException, IllegalBlockSizeException,
InvalidAlgorithmParameterException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchProviderException {
String TRANSFORMATION = ALGORITHM + "/" + mo + "/" + pad;
out.println("Testing: " + TRANSFORMATION);
// Initialization
Cipher ci = Cipher.getInstance(TRANSFORMATION, SUNJCE);
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM, SUNJCE);
if (keySize != 0) {
kg.init(keySize);
}
SecretKey key = kg.generateKey();
SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), ALGORITHM);
AlgorithmParameterSpec aps = new IvParameterSpec(IV);
if (mo.equalsIgnoreCase("ECB")) {
ci.init(Cipher.ENCRYPT_MODE, key);
} else {
ci.init(Cipher.ENCRYPT_MODE, key, aps);
}
// Encryption
byte[] plainText = INPUT_TEXT.clone();
// Generate cipher and save to separate buffer
byte[] cipherText = ci.doFinal(INPUT_TEXT, ENC_OFFSET, TEXT_LEN);
// Generate cipher and save to same buffer
int enc_bytes = ci.update(
INPUT_TEXT, ENC_OFFSET, TEXT_LEN, INPUT_TEXT, STORAGE_OFFSET);
enc_bytes += ci.doFinal(INPUT_TEXT, enc_bytes + STORAGE_OFFSET);
if (!equalsBlock(
INPUT_TEXT, STORAGE_OFFSET, enc_bytes,
cipherText, 0, cipherText.length)) {
throw new RuntimeException(
"Different ciphers generated with same buffer");
}
// Decryption
if (mo.equalsIgnoreCase("ECB")) {
ci.init(Cipher.DECRYPT_MODE, skeySpec);
} else {
ci.init(Cipher.DECRYPT_MODE, skeySpec, aps);
}
// Recover text from cipher and save to separate buffer
byte[] recoveredText = ci.doFinal(cipherText, 0, cipherText.length);
if (!equalsBlock(
plainText, ENC_OFFSET, TEXT_LEN,
recoveredText, 0, recoveredText.length)) {
throw new RuntimeException(
"Recovered text not same as plain text");
} else {
out.println("Recovered and plain text are same");
}
// Recover text from cipher and save to same buffer
int dec_bytes = ci.update(
INPUT_TEXT, STORAGE_OFFSET, enc_bytes, INPUT_TEXT, ENC_OFFSET);
dec_bytes += ci.doFinal(INPUT_TEXT, dec_bytes + ENC_OFFSET);
if (!equalsBlock(
plainText, ENC_OFFSET, TEXT_LEN,
INPUT_TEXT, ENC_OFFSET, dec_bytes)) {
throw new RuntimeException(
"Recovered text not same as plain text with same buffer");
} else {
out.println("Recovered and plain text are same with same buffer");
}
out.println("Test Passed.");
}
public static byte[] generateKey(int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
kg.init(keySize, new SecureRandom());
return kg.generateKey().getEncoded();
}