下面列出了javax.crypto.KeyGenerator#generateKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Generate secret key.
*
* @return the key
* @throws IntegrationModuleException the integration module exception
*/
public Key generateSecretKey() throws IntegrationModuleException {
try {
if (propertyHandler.hasProperty(SYMM_KEY_PROPERTY)) {
String base64key = propertyHandler.getProperty(SYMM_KEY_PROPERTY);
DESedeKeySpec keyspec = new DESedeKeySpec(Base64.decode(base64key));
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
return keyfactory.generateSecret(keyspec);
}
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
return keyGen.generateKey();
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
throw new IntegrationModuleException(e);
}
}
@Deprecated
public Key generateSecretKey() throws TechnicalConnectorException {
TechnicalConnectorExceptionValues errorValue = TechnicalConnectorExceptionValues.ERROR_CRYPTO;
String param = "Could not generate secret key (SymmKey)";
try {
if (config.hasProperty("SYMM_KEY_PROPERTY")) {
String base64key = config.getProperty("SYMM_KEY_PROPERTY");
DESedeKeySpec keyspec = new DESedeKeySpec(Base64.decode(base64key));
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
return keyfactory.generateSecret(keyspec);
} else {
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
return keyGen.generateKey();
}
} catch (Exception var6) {
LOG.debug(MessageFormat.format(errorValue.getMessage(), param));
throw new TechnicalConnectorException(errorValue, var6, new Object[]{param});
}
}
private String createUserSecretKey(long userId) {
try {
UserVO updatedUser = _userDao.createForUpdate();
String encodedKey = null;
int retryLimit = 10;
UserVO userBySecretKey = null;
do {
KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
SecretKey key = generator.generateKey();
encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
userBySecretKey = _userDao.findUserBySecretKey(encodedKey);
retryLimit--;
} while ((userBySecretKey != null) && (retryLimit >= 0));
if (userBySecretKey != null) {
return null;
}
updatedUser.setSecretKey(encodedKey);
_userDao.update(userId, updatedUser);
return encodedKey;
} catch (NoSuchAlgorithmException ex) {
s_logger.error("error generating secret key for user id=" + userId, ex);
}
return null;
}
private static void test(KeyGenerator kg,
int clientVersion, int serverVersion) throws Exception {
System.out.printf(
"Testing RSA pre-master secret key generation between " +
"client (0x%04X) and server(0x%04X)%n",
clientVersion, serverVersion);
kg.init(new TlsRsaPremasterSecretParameterSpec(
clientVersion, serverVersion));
SecretKey key = kg.generateKey();
byte[] encoded = key.getEncoded();
if (encoded != null) { // raw key material may be not extractable
if (encoded.length != 48) {
throw new Exception("length: " + encoded.length);
}
int v = versionOf(encoded[0], encoded[1]);
if (clientVersion != v) {
if (serverVersion != v || clientVersion >= 0x0302) {
throw new Exception(String.format(
"version mismatch: (0x%04X) rather than (0x%04X) " +
"is used in pre-master secret", v, clientVersion));
}
System.out.printf("Use compatible version (0x%04X)%n", v);
}
System.out.println("Passed, version matches!");
} else {
System.out.println("Raw key material is not extractable");
}
}
public SecretKey weakKeySize1() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
keyGen.init(64);
SecretKey key = keyGen.generateKey();
return key;
}
/**
* 加密
*
* @param content 待加密内容
* @param key 加密的密钥
* @return 加密后字符串
*/
public static String encrypt(String content, String key) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key.getBytes(StandardCharsets.UTF_8));
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] byteRresult = cipher.doFinal(byteContent);
StringBuilder sb = new StringBuilder();
for (byte b : byteRresult) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void wrapperAesDESedeKeyTest(String algo, String wrapAlgo,
int keySize) throws InvalidKeyException, NoSuchAlgorithmException,
NoSuchPaddingException, IllegalBlockSizeException,
InvalidAlgorithmParameterException {
// Initialization
KeyGenerator kg = KeyGenerator.getInstance(algo);
if (keySize != -1) {
kg.init(keySize);
}
SecretKey key = kg.generateKey();
wrapTest(algo, wrapAlgo, key, key, Cipher.SECRET_KEY, false);
}
private static 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;
}
/**
* 解密
*
* @param content 待解密内容
* @param key 解密的密钥
* @return 解密后
*/
public static String decrypt(String content, String key) {
if (content.length() < 1) {
return null;
}
byte[] byteResult = new byte[content.length() / 2];
for (int i = 0; i < content.length() / 2; i++) {
int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
byteResult[i] = (byte) (high * 16 + low);
}
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key.getBytes(StandardCharsets.UTF_8));
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] result = cipher.doFinal(byteResult);
return new String(result, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
* HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
*/
public static byte[] generateHmacSha1Key() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* Generate a new AES-256 encryption key
*
* @return a new AES-256 encryption key
*/
@Override
public byte[] generateKey() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException("unable to handle AES encryption", e);
}
}
/**
* 生成AES密钥,可选长度为128,192,256位.
*/
public static byte[] generateAesKey(int keysize) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(keysize);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
} catch (GeneralSecurityException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 初始化HmacMD5密钥
*
* @return
*
* @throws Exception
*/
public static byte[] initHmacMD5Key() throws NoSuchAlgorithmException {
// 初始化KeyGenerator
KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
// 产生秘密密钥
SecretKey secretKey = keyGenerator.generateKey();
// 获得密钥
return secretKey.getEncoded();
}
private static void keyGen() {
try {
final KeyGenerator keyGenny = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
final KeyGenParameterSpec paramSpec = new KeyGenParameterSpec.Builder("Empire", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build();
keyGenny.init(paramSpec);
SecretKey secret = keyGenny.generateKey();
} catch (Exception e) {
System.out.println(e);
}
}
public static SecretKey createKey(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator generator = KeyGenerator.getInstance(algorithm);
return generator.generateKey();
}
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 void main(Provider provider) throws Exception {
if (provider.getService("KeyGenerator", "SunTlsPrf") == null) {
System.out.println("Provider does not support algorithm, skipping");
return;
}
InputStream in = new FileInputStream(new File(BASE, "prfdata.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int n = 0;
int lineNumber = 0;
byte[] secret = null;
String label = null;
byte[] seed = null;
int length = 0;
byte[] output = null;
while (true) {
String line = reader.readLine();
lineNumber++;
if (line == null) {
break;
}
if (line.startsWith("prf-") == false) {
continue;
}
String data = line.substring(PREFIX_LENGTH);
if (line.startsWith("prf-secret:")) {
secret = parse(data);
} else if (line.startsWith("prf-label:")) {
label = data;
} else if (line.startsWith("prf-seed:")) {
seed = parse(data);
} else if (line.startsWith("prf-length:")) {
length = Integer.parseInt(data);
} else if (line.startsWith("prf-output:")) {
output = parse(data);
System.out.print(".");
n++;
KeyGenerator kg =
KeyGenerator.getInstance("SunTlsPrf", provider);
SecretKey inKey;
if (secret == null) {
inKey = null;
} else {
inKey = new SecretKeySpec(secret, "Generic");
}
TlsPrfParameterSpec spec =
new TlsPrfParameterSpec(inKey, label, seed, length,
null, -1, -1);
SecretKey key;
try {
kg.init(spec);
key = kg.generateKey();
} catch (Exception e) {
if (secret == null) {
// This fails on Solaris, but since we never call this
// API for this case in JSSE, ignore the failure.
// (SunJSSE uses the CKM_TLS_KEY_AND_MAC_DERIVE
// mechanism)
System.out.print("X");
continue;
}
System.out.println();
throw new Exception("Error on line: " + lineNumber, e);
}
byte[] enc = key.getEncoded();
if (Arrays.equals(output, enc) == false) {
System.out.println();
System.out.println("expected: " + toString(output));
System.out.println("actual: " + toString(enc));
throw new Exception("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");
}
public static AESKey generate(int bits) throws Exception {
final KeyGenerator keyGen = KeyGenerator.getInstance(AES);
keyGen.init(bits);
final SecretKey secretKey = keyGen.generateKey();
return new AESKey(bits, secretKey);
}
public static void main(String[] args) throws Exception {
Provider provider = Security.getProvider("SunJCE");
InputStream in = new FileInputStream(new File(BASE, "prf12data.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int n = 0;
int lineNumber = 0;
byte[] secret = null;
String label = null;
byte[] seed = null;
int length = 0;
String prfAlg = null;
int prfHashLength = 0;
int prfBlockSize = 0;
byte[] output = null;
while (true) {
String line = reader.readLine();
lineNumber++;
if (line == null) {
break;
}
if (line.startsWith("prf-") == false) {
continue;
}
String data = line.substring(PREFIX_LENGTH);
if (line.startsWith("prf-secret:")) {
secret = parse(data);
} else if (line.startsWith("prf-label:")) {
label = data;
} else if (line.startsWith("prf-seed:")) {
seed = parse(data);
} else if (line.startsWith("prf-length:")) {
length = Integer.parseInt(data);
} else if (line.startsWith("prf-alg:")) {
prfAlg = data;
switch (prfAlg) {
case "SHA-224":
prfHashLength = 28;
prfBlockSize = 64;
break;
case "SHA-256":
prfHashLength = 32;
prfBlockSize = 64;
break;
case "SHA-384":
prfHashLength = 48;
prfBlockSize = 128;
break;
case "SHA-512":
prfHashLength = 64;
prfBlockSize = 128;
break;
default:
throw new Exception("Unknown Alg in the data.");
}
} else if (line.startsWith("prf-output:")) {
output = parse(data);
System.out.print(".");
n++;
KeyGenerator kg =
KeyGenerator.getInstance("SunTls12Prf", provider);
SecretKey inKey;
if (secret == null) {
inKey = null;
} else {
inKey = new SecretKeySpec(secret, "Generic");
}
TlsPrfParameterSpec spec =
new TlsPrfParameterSpec(inKey, label, seed, length,
prfAlg, prfHashLength, prfBlockSize);
kg.init(spec);
SecretKey key = kg.generateKey();
byte[] enc = key.getEncoded();
if (Arrays.equals(output, enc) == false) {
throw new Exception("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");
}
/**
* Generate a secret key.
* @return a {@link SecretKey} instance.
* @throws Exception if any error occurs.
*/
private static SecretKey generateKey() throws Exception {
final KeyGenerator gen = KeyGenerator.getInstance(Helper.getAlgorithm());
return gen.generateKey();
}