Java Code Examples for javax.crypto.KeyGenerator

The following examples show how to use javax.crypto.KeyGenerator. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: UtilsLib   Source File: SecurePreferences.java    License: MIT License 6 votes vote down vote up
@Deprecated
private static String generateAesKeyValue() throws NoSuchAlgorithmException {
    // Do *not* seed secureRandom! Automatically seeded from system entropy
    final SecureRandom random = new SecureRandom();

    // Use the largest AES key length which is supported by the OS
    final KeyGenerator generator = KeyGenerator.getInstance("AES");
    try {
        generator.init(KEY_SIZE, random);
    } catch (Exception e) {
        try {
            generator.init(192, random);
        } catch (Exception e1) {
            generator.init(128, random);
        }
    }
    return SecurePreferences.encode(generator.generateKey().getEncoded());
}
 
Example 2
@BeforeClass
public static void setUpClass() throws Exception {

    //RSA key generation
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    pubKeyRsa = sigPair.getPublic();
    privKeyRsa = sigPair.getPrivate();

    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();

    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    pubKeyEcdsa = keypair.getPublic();
    privKeyEcdsa = keypair.getPrivate();

}
 
Example 3
Source Project: TencentKona-8   Source File: WrongAAD.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example 4
Source Project: j2objc   Source File: CipherOutputStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
private static SecretKey getAndroidKeyStoreSecretKey() throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("AES", "AndroidKeyStore");
    Class<?> keyParamsBuilderClass = keygen.getClass().getClassLoader().loadClass(
            "android.security.keystore.KeyGenParameterSpec$Builder");
    Object keyParamsBuilder = keyParamsBuilderClass.getConstructor(String.class, Integer.TYPE)
            // 3 is PURPOSE_ENCRYPT | PURPOSE_DECRYPT
            .newInstance("testDecryptCorruptGCM", 3);
    keyParamsBuilderClass.getMethod("setBlockModes", new Class[]{String[].class})
            .invoke(keyParamsBuilder, new Object[]{new String[]{"GCM"}});
    keyParamsBuilderClass.getMethod("setEncryptionPaddings", new Class[]{String[].class})
            .invoke(keyParamsBuilder, new Object[]{new String[]{"NoPadding"}});
    AlgorithmParameterSpec spec = (AlgorithmParameterSpec)
            keyParamsBuilderClass.getMethod("build", new Class[]{}).invoke(keyParamsBuilder);
    keygen.init(spec);
    return keygen.generateKey();
}
 
Example 5
public static void encryptIvNotInitialize3(String message) throws Exception {

        //IV
        IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);  //Oups. All 0s

        //Key
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        SecretKey secretKey = generator.generateKey();

        //Encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        cipher.update(message.getBytes());

        byte[] data = cipher.doFinal();
        System.out.println(HexUtil.toString(data));
    }
 
Example 6
Source Project: protools   Source File: ToolDESede.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 生成密钥 <br>
 *
 * @return byte[] 二进制密钥
 *
 * @throws Exception
 */
public static byte[] initKey() throws NoSuchAlgorithmException {

    // 实例化
    KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);

    /*
     * DESede 要求密钥长度为 112位或168位
     */
    kg.init(168);

    // 生成秘密密钥
    SecretKey secretKey = kg.generateKey();

    // 获得密钥的二进制编码形式
    return secretKey.getEncoded();
}
 
Example 7
Source Project: openjdk-jdk8u   Source File: WrongAAD.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example 8
Source Project: taoshop   Source File: AESUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 解密
 * @param encryptBytes
 * @param decryptKey
 * @return
 * @throws Exception
 */
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    //防止linux下 随机生成key
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
    secureRandom.setSeed(decryptKey.getBytes());
    kgen.init(128, secureRandom);
    SecretKey secretKey = kgen.generateKey();
    byte[] enCodeFormat = secretKey.getEncoded();
    SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
    Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
    byte[] result = cipher.doFinal(encryptBytes);

    return new String(result);
}
 
Example 9
Source Project: sakai   Source File: LinkToolUtil.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Generate a secret key, and write it to a file
 * 
 * @param dirname
 *        writes to file privkeyname in this 
 *        directory. dirname assumed to end in /
 */

private static void genkey(String dirname) 
{
	try 
	{
		/* Generate key. */
		log.info("Generating new key in {}{}", dirname, privkeyname);
		SecretKey key = KeyGenerator.getInstance("Blowfish").generateKey();

		/* Write private key to file. */
		writeKey(key, dirname + privkeyname);
	} catch (Exception e) {
		log.debug("Error generating key", e);
	}

}
 
Example 10
Source Project: springboot-shiro   Source File: AesUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 生成加密秘钥
 *
 * @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);
}
 
Example 11
Source Project: jee-universal-bms   Source File: AESUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String StrDecrypt(String content, String secret,String charset){
	try {
		byte[] bytes = Encodes.decodeHex(content);
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		//kgen.init(128, new SecureRandom(authorization.getBytes(charset)));
		SecureRandom secureRandom=
			      SecureRandom.getInstance("SHA1PRNG");
			      secureRandom.setSeed(secret.getBytes(charset));
			      kgen.init(128,secureRandom);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		Cipher cipher = Cipher.getInstance("AES");// 创建密码器
		cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
		byte[] result = cipher.doFinal(bytes);// 加密
		return bytes == null ? null : new String(result, charset);
	} catch (Exception e) {
	}
	return null;
}
 
Example 12
Source Project: lams   Source File: EncryptionUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
public byte[] encrypt(byte[] data, PublicKey publicKey, SecretKey key) throws Exception
{
  // Get the KeyGenerator
   KeyGenerator kgen = KeyGenerator.getInstance(this.encryptionAlgorithm);
   kgen.init(keySize);
 
   byte[] publicKeyEncoded = publicKey.getEncoded();

   SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), encryptionAlgorithm);


   // Instantiate the cipher 
   Cipher cipher = Cipher.getInstance(encryptionAlgorithm);

   cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

   byte[] encrypted =
     cipher.doFinal( data);
   return encrypted;
}
 
Example 13
Source Project: wind-im   Source File: AESCrypto.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 随机生成AES加密解密KEY
 * 
 * @return
 */
public static byte[] generateTSKey() {
	try {
		KeyGenerator kg = KeyGenerator.getInstance("AES");
		kg.init(128);
		SecretKey secretKey = kg.generateKey();
		return secretKey.getEncoded();
	} catch (Exception e) {
		logger.error("generate ts key error", e);
	}
	return null;
}
 
Example 14
Source Project: wind-im   Source File: AESCrypto.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过key生成AES加密解密key
 * 
 * @param key
 * @return
 */
public static byte[] generateTSKey(String key) {
	try {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(key.getBytes(CharsetCoding.ISO_8859_1));
		kgen.init(128, secureRandom);
		SecretKey secretKey = kgen.generateKey();
		return secretKey.getEncoded();
	} catch (Exception e) {
		logger.error("generate ts key error by key=" + key, e);
	}
	return null;
}
 
Example 15
Source Project: jdk8u_jdk   Source File: TestTLS12.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static boolean shouldRun() {
    if (sunPKCS11NSSProvider == null) {
        return false;
    }
    try {
        KeyGenerator.getInstance("SunTls12MasterSecret",
                sunPKCS11NSSProvider);
        KeyGenerator.getInstance(
                "SunTls12RsaPremasterSecret", sunPKCS11NSSProvider);
        KeyGenerator.getInstance("SunTls12Prf", sunPKCS11NSSProvider);
    } catch (NoSuchAlgorithmException e) {
        return false;
    }
    return true;
}
 
Example 16
Source Project: Hive2Hive   Source File: EncryptionUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Generates a symmetric AES key of the specified key length.
 * 
 * @param keyLength The length the AES key should have.
 * @param securityProvider the security provider (e.g. "BC" for bouncy castle)
 * @return A symmetric AES key of the specified length.
 */
public static SecretKey generateAESKey(AES_KEYLENGTH keyLength, String securityProvider) {
	try {
		final KeyGenerator kg = KeyGenerator.getInstance("AES", securityProvider);
		kg.init(keyLength.value(), new SecureRandom());
		byte[] encoded = kg.generateKey().getEncoded();
		return new SecretKeySpec(encoded, "AES");
	} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
		logger.error("Exception while AES key generator instance creation:", e);
	}
	return null;

}
 
Example 17
@BeforeClass
public static void setUpClass() throws NoSuchAlgorithmException {
    rnd = new SecureRandom();
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, rnd);
    sigPair = rsaGen.generateKeyPair();
    
    KeyGenerator aesGen = KeyGenerator.getInstance("AES");
    aesGen.init(128, rnd);
    encryptionKey = aesGen.generateKey();
    
    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, rnd);
    macKey = macGen.generateKey();
}
 
Example 18
Source Project: weMessage   Source File: AESCrypto.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * A function that generates random AES & HMAC keys and prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @return The AES & HMAC keys.
 * @throws GeneralSecurityException if AES is not implemented on this system,
 *                                  or a suitable RNG is not available
 */
public static SecretKeys generateKeys() throws GeneralSecurityException {
    fixPrng();
    KeyGenerator keyGen = KeyGenerator.getInstance(CIPHER);
    // No need to provide a SecureRandom or set a seed since that will
    // happen automatically.
    keyGen.init(AES_KEY_LENGTH_BITS);
    SecretKey confidentialityKey = keyGen.generateKey();

    //Now make the HMAC key
    byte[] integrityKeyBytes = randomBytes(HMAC_KEY_LENGTH_BITS / 8);//to get bytes
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
 
Example 19
private static byte[] generateEncryptionSecret() {
  try {
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(256);

    SecretKey key = generator.generateKey();
    return key.getEncoded();
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 20
private static byte[] generateMacSecret() {
  try {
    KeyGenerator generator = KeyGenerator.getInstance("HmacSHA256");

    SecretKey key = generator.generateKey();
    return key.getEncoded();
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 21
Source Project: Open-Lowcode   Source File: AESCommunicator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * perform an handshake with the server to get and send back to the server an
 * AES Key
 * 
 * @param reader message reader connected with the server
 * @param writer message writer connected with the server
 * @return the AES communicator allowing encryption for communication with the
 *         server
 * @throws Exception if any communication error is encountered
 */
public static AESCommunicator performServerHandshake(MessageSimpleReader reader, MessageBufferedWriter writer)
		throws Exception {
	reader.returnNextMessageStart();
	reader.returnNextStartStructure("RSAKEY");
	byte[] rsapublickey = reader.returnNextLargeBinary("PUBLICKEY").getContent();
	reader.returnNextEndStructure("RSAKEY");
	reader.returnNextEndMessage();

	// ----------------------Generate AES Key --------------------------------------
	KeyGenerator keyGen = KeyGenerator.getInstance("AES");
	keyGen.init(256);
	SecretKey secretKey = keyGen.generateKey();
	byte[] aeskey = secretKey.getEncoded();

	// ----------- keep AES keys ----
	AESCommunicator aescommunicator = new AESCommunicator(secretKey);
	// --- Encrypt AES key with RSA key ----

	KeyFactory kf = KeyFactory.getInstance("RSA");
	PublicKey rsapublickeyasobject = kf.generatePublic(new X509EncodedKeySpec(rsapublickey));
	Cipher encryptrsacipher = Cipher.getInstance("RSA");
	encryptrsacipher.init(Cipher.ENCRYPT_MODE, rsapublickeyasobject);
	byte[] aeskeyencoded = encryptrsacipher.doFinal(aeskey);
	writer.startNewMessage();
	writer.startStructure("SESAESKEY");
	writer.addLongBinaryField("AESKEY", new SFile("Aeskey", aeskeyencoded));
	writer.endStructure("SESAESKEY");
	writer.endMessage();
	return aescommunicator;
}
 
Example 22
Source Project: openjdk-jdk9   Source File: Encrypt.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param provider Security provider
 * @param algorithm Security algorithm to test
 * @param mode The mode (GCM is only expected)
 * @param padding Algorithm padding
 * @param keyStrength key length
 * @param textLength Plain text length
 * @param AADLength Additional data length
 */
public Encrypt(Provider provider, String algorithm, String mode,
        String padding, int keyStrength, int textLength, int AADLength)
        throws Exception {

    // init a secret Key
    KeyGenerator kg = KeyGenerator.getInstance(algorithm, provider);
    kg.init(keyStrength);
    key = kg.generateKey();

    this.provider = provider;
    this.transformation = algorithm + "/" + mode + "/" + padding;
    this.textLength = textLength;
    this.AADLength = AADLength;
}
 
Example 23
Source Project: elemeimitate   Source File: AESEncryptor.java    License: Apache License 2.0 5 votes vote down vote up
private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom 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;
}
 
Example 24
Source Project: presto   Source File: AesSpillCipher.java    License: Apache License 2.0 5 votes vote down vote up
private static SecretKey generateNewSecretKey()
{
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(KEY_BITS);
        return keyGenerator.generateKey();
    }
    catch (NoSuchAlgorithmException e) {
        throw new PrestoException(GENERIC_INTERNAL_ERROR, "Failed to generate new secret key: " + e.getMessage(), e);
    }
}
 
Example 25
Source Project: XDroidMvp   Source File: Codec.java    License: MIT License 5 votes vote down vote up
/**
 * 初始化HMAC密钥
 *
 * @param algorithm 算法,可为空。默认为:Algorithm.Hmac_MD5
 * @return
 * @throws Exception
 */
public static String initMacKey(Algorithm algorithm) throws Exception {
    if (algorithm == null) algorithm = Algorithm.Hmac_MD5;
    KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm.getType());
    SecretKey secretKey = keyGenerator.generateKey();

    return BASE64.encodeToString(secretKey.getEncoded());
}
 
Example 26
Source Project: EasyML   Source File: Aes.java    License: Apache License 2.0 5 votes vote down vote up
/** 
 * Aes Encryption 
 * @param content content to be encrypted
 * @param encryptKey encryption key
 * @return 
 * @throws Exception 
 */  
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {  
    KeyGenerator kgen = KeyGenerator.getInstance("AES");  
    kgen.init(128);  
    Cipher cipher = Cipher.getInstance(ALGORITHMSTR);  
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));  
  
    return cipher.doFinal(content.getBytes("utf-8"));  
}
 
Example 27
Source Project: azure-keyvault-java   Source File: AesValidationTests.java    License: MIT License 5 votes vote down vote up
private static JsonWebKey getAes() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance(TRANSFORMATION);
    keyGen.init(256);
    
    SecretKey skey = keyGen.generateKey();        
    return JsonWebKey.fromAes(skey);
}
 
Example 28
Source Project: cxf   Source File: SymmetricBindingHandler.java    License: Apache License 2.0 5 votes vote down vote up
private String setupEncryptedKey(AbstractTokenWrapper wrapper, AbstractToken sigToken) throws WSSecurityException {
    AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
    KeyGenerator keyGen = KeyUtils.getKeyGenerator(algType.getEncryption());
    SecretKey symmetricKey = keyGen.generateKey();

    WSSecEncryptedKey encrKey = this.getEncryptedKeyBuilder(sigToken, symmetricKey);
    assertTokenWrapper(wrapper);
    String id = encrKey.getId();
    byte[] secret = symmetricKey.getEncoded();

    Instant created = Instant.now();
    Instant expires = created.plusSeconds(WSS4JUtils.getSecurityTokenLifetime(message) / 1000L);
    SecurityToken tempTok = new SecurityToken(
                    id,
                    encrKey.getEncryptedKeyElement(),
                    created,
                    expires);


    tempTok.setSecret(secret);

    // Set the SHA1 value of the encrypted key, this is used when the encrypted
    // key is referenced via a key identifier of type EncryptedKeySHA1
    tempTok.setSHA1(encrKey.getEncryptedKeySHA1());
    tokenStore.add(tempTok);

    // Create another cache entry with the SHA1 Identifier as the key for easy retrieval
    tokenStore.add(tempTok.getSHA1(), tempTok);

    String bstTokenId = encrKey.getBSTTokenId();
    //If direct ref is used to refer to the cert
    //then add the cert to the sec header now
    if (bstTokenId != null && bstTokenId.length() > 0) {
        encrKey.prependBSTElementToHeader();
    }
    return id;
}
 
Example 29
private static SecretKey generateSecretKey() throws EncryptionException {
    try {
        KeyGenerator generator = KeyGenerator.getInstance(SYMMETRIC_KEY_TYPE);
        generator.init(SYMMETRIC_KEY_SIZE);
        return generator.generateKey();
    } catch (GeneralSecurityException e) {
        throw new EncryptionException("Failed to generate a secret key!", e);
    }
}
 
Example 30
Source Project: bcm-android   Source File: MasterSecretUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static byte[] generateMacSecret() {
    try {
        KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
        return generator.generateKey().getEncoded();
    } catch (NoSuchAlgorithmException e) {
        Log.w("keyutil", e);
        return null;
    }
}