Java Code Examples for javax.crypto.SecretKeyFactory#getInstance()

The following examples show how to use javax.crypto.SecretKeyFactory#getInstance() . 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 File: VncClient.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
/**
 * Encode password using DES encryption with given challenge.
 *
 * @param challenge
 *            a random set of bytes.
 * @param password
 *            a password
 * @return DES hash of password and challenge
 */
public byte[] encodePassword(byte[] challenge, String password) throws Exception {
    // VNC password consist of up to eight ASCII characters.
    byte[] key = {0, 0, 0, 0, 0, 0, 0, 0}; // Padding
    byte[] passwordAsciiBytes = password.getBytes(RfbConstants.CHARSET);
    System.arraycopy(passwordAsciiBytes, 0, key, 0, Math.min(password.length(), 8));

    // Flip bytes (reverse bits) in key
    for (int i = 0; i < key.length; i++) {
        key[i] = flipByte(key[i]);
    }

    KeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
    Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    byte[] response = cipher.doFinal(challenge);
    return response;
}
 
Example 2
Source File: AesCbcWithIntegrity.java    From android-utils with Apache License 2.0 6 votes vote down vote up
/**
 * A function that generates password-based AES & HMAC keys. It prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @param password The password to derive the keys from.
 * @param salt     the salt
 * @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 generateKeyFromPassword(String password, byte[] salt)
        throws GeneralSecurityException {
    fixPrng();
    //Get enough random bytes for both the AES key and the HMAC key:
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT,
            AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM);
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();

    // Split the random bytes into two parts:
    byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS / 8);
    byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS / 8,
            AES_KEY_LENGTH_BITS / 8 + HMAC_KEY_LENGTH_BITS / 8);

    //Generate the AES key
    SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER);

    //Generate the HMAC key
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
 
Example 3
Source File: DESUtil.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * DES解密方法
 * @param message
 * @param key
 * @return
 * @throws Exception
 */
public static String decrypt(String message, String key) throws Exception {

	byte[] bytesrc = convertHexString(message);
	byte[] theKey = null;
	String jqstr = getstrByte(key).substring(0,
			8).toUpperCase();
	theKey = jqstr.getBytes(ENCODED_ASCII);
	Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE_CBC);
	DESKeySpec desKeySpec = new DESKeySpec(theKey);
	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
	IvParameterSpec iv = new IvParameterSpec(theKey);

	cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

	byte[] retByte = cipher.doFinal(bytesrc);
	return new String(retByte,ENCODED_GB2312);
}
 
Example 4
Source File: CyptoUtils.java    From MissZzzReader with Apache License 2.0 6 votes vote down vote up
/**
 * DES算法,解密
 *
 * @param data 待解密字符串
 * @param key  解密私钥,长度不能够小于8位
 * @return 解密后的字节数组
 * @throws Exception 异常
 */
public static byte[] decodeToByte(String key, byte[] data) {
	if(data == null)
		return null;
	try {
		DESKeySpec dks = new DESKeySpec(key.getBytes());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		//key的长度不能够小于8位字节
		Key secretKey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
		IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
		AlgorithmParameterSpec paramSpec = iv;
		cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
		return cipher.doFinal(hex2byte(data));
	} catch (Exception e){
		e.printStackTrace();
		return null;
	}
}
 
Example 5
Source File: DesUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * Description 根据键值进行解密
 * @param data
 * @param key  加密键byte数组
 * @return
 * @throws Exception
 */
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
	// 生成一个可信任的随机数源
	SecureRandom sr = new SecureRandom();
	
	// 从原始密钥数据创建DESKeySpec对象
	DESKeySpec dks = new DESKeySpec(key);
	
	// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	SecretKey securekey = keyFactory.generateSecret(dks);
	
	// Cipher对象实际完成解密操作
	Cipher cipher = Cipher.getInstance(DES);
	
	// 用密钥初始化Cipher对象
	cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
	
	return cipher.doFinal(data);
}
 
Example 6
Source File: DESCoder.java    From ToolsFinal with Apache License 2.0 6 votes vote down vote up
/**
 * 加密
 * @param data
 * @param password
 * @return
 */
public static byte[] encrypt(byte[] data, String password) {
    try {
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        //创建一个密匙工厂,然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        //Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");
        //用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        //现在,获取数据并加密
        //正式执行加密操作
        return cipher.doFinal(data);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 7
Source File: TestCipherKeyWrapperTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
        InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException {
    for (String alg : PBE_ALGORITHM_AR) {
        String baseAlgo = alg.split("/")[0].toUpperCase();
        // only run the tests on longer key lengths if unlimited version
        // of JCE jurisdiction policy files are installed

        if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
                && (baseAlgo.endsWith("TRIPLEDES") || alg
                        .endsWith("AES_256"))) {
            out.println("keyStrength > 128 within " + alg
                    + " will not run under global policy");
            continue;
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
                .toCharArray()));
        wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
    }
}
 
Example 8
Source File: PBKDF2Translate.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The test case scenario implemented in the method: - create my own secret
 * Key2 as an instance of a class implements PBEKey - spoil the key (set
 * iteration count to 0, for example) - try to translate key -
 * InvalidKeyException is expected.
 *
 * @return true if InvalidKeyException occurred; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public boolean translateSpoiledKey() throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    // derive the key
    SecretKey key1 = getMyOwnSecretKey();

    // spoil the key
    ((MyPBKDF2SecretKey) key1).spoil();

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    try {
        SecretKey key2 = skf.translateKey(key1);
    } catch (InvalidKeyException ike) {
        // this is expected
        return true;
    }

    return false;
}
 
Example 9
Source File: DESUtil.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * DES解密方法
 * @param message
 * @param key
 * @return
 * @throws Exception
 */
public static String decrypt(String message, String key) throws Exception {

	byte[] bytesrc = convertHexString(message);
	byte[] theKey = null;
	String jqstr = getstrByte(key).substring(0,
			8).toUpperCase();
	theKey = jqstr.getBytes(ENCODED_ASCII);
	Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE_CBC);
	DESKeySpec desKeySpec = new DESKeySpec(theKey);
	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
	IvParameterSpec iv = new IvParameterSpec(theKey);

	cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

	byte[] retByte = cipher.doFinal(bytesrc);
	return new String(retByte,ENCODED_GB2312);
}
 
Example 10
Source File: PageTokenManager.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String encrypt(String property) {
	SecretKeyFactory keyFactory;
	try {
		keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey key = keyFactory.generateSecret(new PBEKeySpec(this.getPasswordCharArray()));
		Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

		pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(this.getSalt().getBytes(), 20));
		return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));

	} catch (GeneralSecurityException | UnsupportedEncodingException e) {
		logger.error("Error in encrypt", e);
	}
	return null;
}
 
Example 11
Source File: PBKDF2Translate.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The test case scenario implemented in the method: - derive PBKDF2 key
 * using the given algorithm; - translate the key - check if the translated
 * and original keys have the same key value.
 *
 * @return true if the test case passed; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 */
public boolean generateAndTranslateKey() throws NoSuchAlgorithmException,
        InvalidKeySpecException, InvalidKeyException {
    // derive PBKDF2 key
    SecretKey key1 = getSecretKeyForPBKDF2(algoToTest);

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    SecretKey key2 = skf.translateKey(key1);

    // check if it still the same after translation
    if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
        System.err.println("generateAndTranslateKey test case failed: the "
                + "key1 and key2 values in its primary encoding format are "
                + "not the same for " + algoToTest + "algorithm.");
        return false;
    }

    return true;
}
 
Example 12
Source File: PBKDF2TranslateTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The test case scenario implemented in the method: - derive Key1 for the
 * given PBKDF2 algorithm - create my own secret Key2 as an instance of a
 * class implements PBEKey - translate Key2 - check if the key value of the
 * translated key and Key1 are the same.
 */
private void testMyOwnSecretKey(byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException,
        InvalidKeyException {
    SecretKey key1 = getSecretKeyForPBKDF2(algoForTest, salt);
    SecretKey key2 = getMyOwnSecretKey(salt);

    // Is it actually the same?
    if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
        throw new RuntimeException(
                "We shouldn't be here. The key1 and key2 values in its"
                        + " primary encoding format have to be the same!");
    }

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest);
    SecretKey key3 = skf.translateKey(key2);

    // Check if it still the same after translation
    if (!Arrays.equals(key1.getEncoded(), key3.getEncoded())) {
        System.out.println("Key1=" + new String(key1.getEncoded())
                + " key3=" + new String(key3.getEncoded()) + " salt="
                + new String(salt));
        throw new RuntimeException(
                "testMyOwnSecretKey test case failed: the key1  and key3"
                        + " values in its primary encoding format are not"
                        + " the same for " + algoForTest + " algorithm.");
    }

}
 
Example 13
Source File: SecKFTranslateTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(Algorithm algo) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException,
        InvalidKeySpecException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, ShortBufferException,
        IllegalBlockSizeException, BadPaddingException {
    AlgorithmParameterSpec[] aps = new AlgorithmParameterSpec[1];
    byte[] plainText = new byte[800];

    SecretKey key1 = algo.intSecurityKey(aps);
    Random random = new Random();
    // Initialization
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.toString(),
            SUN_JCE);

    random.nextBytes(plainText);
    Cipher ci = Cipher.getInstance(algo.toString(), SUN_JCE);
    // Encryption
    ci.init(Cipher.ENCRYPT_MODE, key1, aps[0]);
    byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
    int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
    ci.doFinal(cipherText, offset);
    // translate key
    SecretKey key2 = skf.translateKey(key1);

    // Decryption
    ci.init(Cipher.DECRYPT_MODE, key2, aps[0]);
    byte[] recoveredText = new byte[ci.getOutputSize(plainText.length)];
    ci.doFinal(cipherText, 0, cipherText.length, recoveredText);

    // Comparison
    if (!Arrays.equals(plainText, recoveredText)) {
        System.out.println("Key1:" + new String(key1.getEncoded())
                + " Key2:" + new String(key2.getEncoded()));
        throw new RuntimeException("Testing translate key failed with "
                + algo);
    }

}
 
Example 14
Source File: DESCoder.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
private byte[] doEncrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    SecureRandom random = new SecureRandom();
    DESKeySpec desKey = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CIPHER_ALGORITHM);

    SecretKey securekey = keyFactory.generateSecret(desKey);

    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

    cipher.init(Cipher.ENCRYPT_MODE, securekey, random);

    return cipher.doFinal(data);
}
 
Example 15
Source File: PBKDF2Translate.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate a PBKDF2 secret key using given algorithm.
 *
 * @param algoToDeriveKey PBKDF2 algorithm
 * @return PBKDF2 secret key
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private SecretKey getSecretKeyForPBKDF2(String algoToDeriveKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToDeriveKey);

    PBEKeySpec spec = new PBEKeySpec(PASS_PHRASE.toCharArray(),
            this.salt, ITERATION_COUNT, KEY_SIZE);

    return skf.generateSecret(spec);
}
 
Example 16
Source File: PBEIdentityLoginModule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String encode(String secret)
   throws Exception
{
   // Create the PBE secret key
   cipherSpec = new PBEParameterSpec(salt, iterationCount);
   PBEKeySpec keySpec = new PBEKeySpec(pbepass);
   SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
   SecretKey cipherKey = factory.generateSecret(keySpec);

   // Decode the secret
   Cipher cipher = Cipher.getInstance(pbealgo);
   cipher.init(Cipher.ENCRYPT_MODE, cipherKey, cipherSpec);
   byte[] encoding = cipher.doFinal(secret.getBytes());
   return Base64Utils.tob64(encoding);
}
 
Example 17
Source File: PBKDF2Hash.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the PBKDF2 hash of a password.
 *
 * @param password   the password to hash.
 * @param salt       the salt
 * @param iterations the iteration count (slowness factor)
 * @param bytes      the length of the hash to compute in bytes
 * @return the PBDKF2 hash of the password
 */
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) {
    PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    SecretKeyFactory skf = null;
    try {
        skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
        return skf.generateSecret(spec).getEncoded();
    } catch (NoSuchAlgorithmException ignore) {
        return null;
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 18
Source File: ExportBackupService.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] getKey(final String password, final byte[] salt) throws InvalidKeySpecException {
    final SecretKeyFactory factory;
    try {
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
    return factory.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 1024, 128)).getEncoded();
}
 
Example 19
Source File: PasswordHash.java    From db with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Computes the PBKDF2 hash of a password.
 *
 * @param password the password to hash.
 * @param salt the salt
 * @param iterations the iteration count (slowness factor)
 * @param bytes the length of the hash to compute in bytes
 * @return the PBDKF2 hash of the password
 */
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
    return skf.generateSecret(spec).getEncoded();
}
 
Example 20
Source File: CipherUtils.java    From VideoMeeting with Apache License 2.0 2 votes vote down vote up
/**
 * 返回可逆算法DES的密钥
 * 
 * @param key
 *            前8字节将被用来生成密钥。
 * @return 生成的密钥
 * @throws Exception
 */
public static Key getDESKey(byte[] key) throws Exception {
    DESKeySpec des = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    return keyFactory.generateSecret(des);
}