本文整理汇总了Java中javax.crypto.KeyGenerator类的典型用法代码示例。如果您正苦于以下问题:Java KeyGenerator类的具体用法?Java KeyGenerator怎么用?Java KeyGenerator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
KeyGenerator类属于javax.crypto包,在下文中一共展示了KeyGenerator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: encryptData
import javax.crypto.KeyGenerator; //导入依赖的package包/类
@Override
public void encryptData(String plaintext) {
System.out.println("-------Encrypting data using AES algorithm-------");
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
byte[] plaintTextByteArray = plaintext.getBytes("UTF8");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plaintTextByteArray);
System.out.println("Original data: " + plaintext);
System.out.println("Encrypted data:");
for (int i = 0; i < cipherText.length; i++) {
System.out.print(cipherText[i] + " ");
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
示例2: main
import javax.crypto.KeyGenerator; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
Provider provider = Security.getProvider("SunJCE");
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.");
}
示例3: createNewKey
import javax.crypto.KeyGenerator; //导入依赖的package包/类
/**
* Create a new key in the Keystore
*/
private void createNewKey(){
try {
final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);
final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
// Build one key to be used for encrypting and decrypting the file
keyGenerator.init(
new KeyGenParameterSpec.Builder(ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build());
keyGenerator.generateKey();
Log.i(TAG, "Key created in Keystore");
}catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException kS){
Log.e(TAG, kS.getMessage());
}
}
示例4: DESCipherWrapper
import javax.crypto.KeyGenerator; //导入依赖的package包/类
public DESCipherWrapper(String algo, String mode, String pad)
throws NoSuchAlgorithmException, NoSuchPaddingException {
ci = Cipher.getInstance(algo + "/" + mode + "/" + pad);
iv = new byte[8];
for (int i = 0; i < 8; i++) {
iv[i] = (byte) (i & 0xff);
}
KeyGenerator kg = KeyGenerator.getInstance(algo);
key = kg.generateKey();
keyStrength = algo.equalsIgnoreCase("DESede") ? 112
: key.getEncoded().length * 8;
this.algo = algo;
this.mode = mode;
this.pad = pad;
}
示例5: triggerMacKeyGeneration
import javax.crypto.KeyGenerator; //导入依赖的package包/类
/**
* Generates the authentication encryption key in a background thread (if necessary).
*/
private static void triggerMacKeyGeneration() {
synchronized (sLock) {
if (sKey != null || sMacKeyGenerator != null) {
return;
}
sMacKeyGenerator = new FutureTask<SecretKey>(new Callable<SecretKey>() {
// SecureRandomInitializer addresses the bug in SecureRandom that "TrulyRandom"
// warns about, so this lint warning can safely be suppressed.
@SuppressLint("TrulyRandom")
@Override
public SecretKey call() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance(MAC_ALGORITHM_NAME);
SecureRandom random = new SecureRandom();
SecureRandomInitializer.initialize(random);
generator.init(MAC_KEY_BYTE_COUNT * 8, random);
return generator.generateKey();
}
});
AsyncTask.THREAD_POOL_EXECUTOR.execute(sMacKeyGenerator);
}
}
示例6: AesDecrypt
import javax.crypto.KeyGenerator; //导入依赖的package包/类
/**
* aes解密-128位
*/
public static String AesDecrypt(String encryptContent, String password) {
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
keyGen.init(128, secureRandom);
SecretKey secretKey = keyGen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(hex2Bytes(encryptContent)));
} catch (Exception e) {
logger.error("AesDecrypt exception", e);
return null;
}
}
示例7: aesEncryptToBytes
import javax.crypto.KeyGenerator; //导入依赖的package包/类
private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(encryptKey.getBytes()));
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
示例8: getKey
import javax.crypto.KeyGenerator; //导入依赖的package包/类
private static SecretKey getKey(byte[] seed)
{
try
{
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(seed);
keyGenerator.init(128, secureRandom); // 128 is the safest one to
// use for compatibility?
SecretKey skey = keyGenerator.generateKey();
return skey;
}
catch (Exception ex)
{
Logger.debug(ex, Encryption.class);
}
return null;
}
示例9: initFingerprintManager
import javax.crypto.KeyGenerator; //导入依赖的package包/类
private void initFingerprintManager() throws Throwable {
mFpManager = (FingerprintManager) mContext.getSystemService(Context.FINGERPRINT_SERVICE);
if (!mFpManager.isHardwareDetected())
throw new IllegalStateException("Fingerprint hardware not present");
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
KeyGenerator keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
keyStore.load(null);
keyGenerator.init(new KeyGenParameterSpec.Builder(
KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/" +
KeyProperties.BLOCK_MODE_CBC + "/" +
KeyProperties.ENCRYPTION_PADDING_PKCS7);
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
cipher.init(Cipher.ENCRYPT_MODE, key);
mFpHandler = new FingerprintHandler(cipher);
if (DEBUG) log("Fingeprint manager initialized");
}
示例10: getRawKey
import javax.crypto.KeyGenerator; //导入依赖的package包/类
/**
* 获取256位的加密密钥
*
* @param seed
* @return
* @throws Exception
*/
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = null;
// 在4.2以上版本中,SecureRandom获取方式发生了改变
if (android.os.Build.VERSION.SDK_INT >= JELLY_BEAN_4_2) {
sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
} else {
sr = SecureRandom.getInstance("SHA1PRNG");
}
sr.setSeed(seed);
// 256 bits or 128 bits,192bits
kgen.init(256, sr);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
示例11: WrongAAD
import javax.crypto.KeyGenerator; //导入依赖的package包/类
public WrongAAD() throws Exception {
// init a secret key
KeyGenerator kg = KeyGenerator.getInstance("AES", PROVIDER);
kg.init(KEY_SIZE);
key = kg.generateKey();
// generate a plain text
plainText = Helper.generateBytes(TEXT_SIZE);
// init AADs
byte[] AAD = Helper.generateBytes(AAD_SIZE);
// init a cipher
encryptCipher = createCipher(Cipher.ENCRYPT_MODE, null);
encryptCipher.updateAAD(AAD);
}
示例12: initKey
import javax.crypto.KeyGenerator; //导入依赖的package包/类
/**
* 生成密钥 <br>
* Java 6 只支持56bit密钥 <br>
* Bouncy Castle 支持64bit密钥 <br>
*
* @return byte[] 二进制密钥
* @throws NoSuchAlgorithmException
*/
public static byte[] initKey() throws NoSuchAlgorithmException {
/*
* 实例化密钥生成器
*
* 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
* 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
*/
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
/*
* 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);
*/
kg.init(56, new SecureRandom());
// 生成秘密密钥
SecretKey secretKey = kg.generateKey();
// 获得密钥的二进制编码形式
return secretKey.getEncoded();
}
示例13: getOrCreateSecretKey
import javax.crypto.KeyGenerator; //导入依赖的package包/类
private SecretKey getOrCreateSecretKey(String alias) throws GeneralSecurityException, IOException {
try {
return getSymmetricKey(alias);
} catch (FileNotFoundException fnfe) {
Log.i(Constants.TAG, "no existing symmetric key for alias");
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
//32bytes / 256bits AES key
keyGenerator.init(256);
SecretKey secretKey = keyGenerator.generateKey();
PublicKey publicKey = getOrCreatePublicKey(alias);
Storage.writeValues(getContext(), Constants.SKS_KEY_FILENAME + alias,
encryptRsaPlainText(publicKey, secretKey.getEncoded()));
Log.i(Constants.TAG, "created new symmetric keys for alias");
return secretKey;
}
}
示例14: createCipherKeyGenerator
import javax.crypto.KeyGenerator; //导入依赖的package包/类
private void createCipherKeyGenerator(){
if(cipherKeyGenCreated){
return;
}
try {
cipherKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, provider);
cipherKeyGenerator.init(new KeyGenParameterSpec.Builder(keyName,KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
cipherKeyGenCreated = true;
} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
throw new RuntimeException("Failed to create key generator", e);
}
}
示例15: initKey
import javax.crypto.KeyGenerator; //导入依赖的package包/类
/**
* 生成密钥 <br>
* Java 6 只支持56bit密钥 <br>
* Bouncy Castle 支持64bit密钥 <br>
*
* @return byte[] 二进制密钥
* @throws NoSuchAlgorithmException
* @throws Exception
*/
public static byte[] initKey() throws NoSuchAlgorithmException {
/*
* 实例化密钥生成器
*
* 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
* 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
*/
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
/*
* 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);
*/
kg.init(56, new SecureRandom());
// 生成秘密密钥
SecretKey secretKey = kg.generateKey();
// 获得密钥的二进制编码形式
return secretKey.getEncoded();
}