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

The following examples show how to use javax.crypto.SecretKeyFactory#generateSecret() . 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: PBKDF2Translate.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The key is generating by SecretKeyFactory and its value just copying in
 * the key field of MySecretKey class. So, this is real key derived using
 * the given algorithm.
 *
 * @param passPhrase some string intended to be a password
 * @param algo PBKDF2 algorithm
 * @param salt slat for PBKDF2
 * @param iterationCount iteration count
 * @param keySize key size in bits
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 */
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt,
        int iterationCount, int keySize)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    this.algorithm = algo;
    this.salt = salt;
    this.itereationCount = iterationCount;
    this.keySize = keySize;
    this.pass = passPhrase;

    PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(),
            this.salt, iterationCount, this.keySize);

    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(algo);

    SecretKey realKey = keyFactory.generateSecret(spec);

    this.keyLength = realKey.getEncoded().length;

    this.key = new byte[this.keyLength];
    System.arraycopy(realKey.getEncoded(), 0, this.key, 0,
            this.keyLength);
}
 
Example 2
Source File: PBKDF2TranslateTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The key is generating by SecretKeyFactory and its value just copying
 * in the key field of MySecretKey class. So, this is real key derived
 * using the given algo.
 */
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1,
        int iterationCount, int keySize)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    algorithm = algo;
    salt = salt1;
    itereationCount = iterationCount;
    pass = passPhrase;

    PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt,
            iterationCount, keySize);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);

    SecretKey realKey = keyFactory.generateSecret(spec);

    keyLength = realKey.getEncoded().length;

    key = new byte[keyLength];
    System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength);
}
 
Example 3
Source File: DES.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
/**
 * DES算法,解密
 *
 * @param data 待解密字符串
 * @param key  解密私钥,长度不能够小于8位
 * @return 解密后的字节数组
 * @throws Exception 异常
 */
public static String decrypt(String key,String 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);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV_PARAMS_BYTES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        return new String(cipher.doFinal(hex2byte(data.getBytes())));
    } catch (Exception e){
    	throw new RuntimeException(e);
    }
}
 
Example 4
Source File: Des3DkCrypto.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
    throws GeneralSecurityException {
    // NoSuchAlgorithException
    SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");

    // InvalidKeyException
    KeySpec spec = new DESedeKeySpec(key, 0);

    // InvalidKeySpecException
    SecretKey secretKey = factory.generateSecret(spec);

    // IV
    if (ivec == null) {
        ivec = ZERO_IV;
    }

    // NoSuchAlgorithmException, NoSuchPaddingException
    // NoSuchProviderException
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);

    // InvalidKeyException, InvalidAlgorithParameterException
    cipher.init(mode, secretKey, encIv);

    return cipher;
}
 
Example 5
Source File: DataCipher.java    From onboard with Apache License 2.0 6 votes vote down vote up
/**
 * 解密方法
 * 
 */
private static byte[] decrypt(byte[] encryptedData) throws IllegalBlockSizeException, BadPaddingException,
        InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
    // DES算法要求有一个可信任的随机数源
    SecureRandom sr = new SecureRandom();
    // 从原始密匙数据创建一个DESKeySpec对象
    DESKeySpec dks = new DESKeySpec(getRawKeyData());
    // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成一个SecretKey对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(dks);
    // Cipher对象实际完成解密操作
    Cipher cipher = Cipher.getInstance("DES");
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.DECRYPT_MODE, key, sr);
    // 正式执行解密操作
    byte decryptedData[] = cipher.doFinal(encryptedData);
    return decryptedData;
}
 
Example 6
Source File: Des3DkCrypto.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
    throws GeneralSecurityException {
    // NoSuchAlgorithException
    SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");

    // InvalidKeyException
    KeySpec spec = new DESedeKeySpec(key, 0);

    // InvalidKeySpecException
    SecretKey secretKey = factory.generateSecret(spec);

    // IV
    if (ivec == null) {
        ivec = ZERO_IV;
    }

    // NoSuchAlgorithmException, NoSuchPaddingException
    // NoSuchProviderException
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);

    // InvalidKeyException, InvalidAlgorithParameterException
    cipher.init(mode, secretKey, encIv);

    return cipher;
}
 
Example 7
Source File: DESEncrypt.java    From SprintNBA with Apache License 2.0 6 votes vote down vote up
public static String encode(String key, String 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.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return byte2hex(bytes);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
 
Example 8
Source File: AbstractCrypto.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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});
   }
}
 
Example 9
Source File: DESUtil.java    From Encrypt with Apache License 2.0 6 votes vote down vote up
/**
 * DES����
 * 
 * @param HexString
 *            �ַ�����16λ16�����ַ�����
 * @param keyStr
 *            ��Կ16��1
 * @throws Exception
 */
public static String ENCRYPTMethod(String HexString, String keyStr)
		throws Exception {
	String jmstr = "";
	try {
		byte[] theKey = null;
		String jqstr = getstrByte(keyStr).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.ENCRYPT_MODE, secretKey, iv);
		byte[] theCph = cipher.doFinal(HexString.getBytes(ENCODED_GB2312));
		jmstr = toHexString(theCph).toUpperCase();
		jmstr = toHexString(theCph);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
	return jmstr;
}
 
Example 10
Source File: PBMacBuffer.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get SecretKey for the given PBKDF2 algorithm.
 *
 * @param thePBKDF2Algorithm - PBKDF2 algorithm
 * @return SecretKey according to thePBKDF2Algorithm
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
protected SecretKey getSecretKey(String thePBKDF2Algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Prepare salt
    byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation
    new SecureRandom().nextBytes(salt);

    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(
            "A #pwd# implied to be hidden!".toCharArray(),
            salt, 1000, 128);
    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(thePBKDF2Algorithm);
    return keyFactory.generateSecret(pbeKeySpec);
}
 
Example 11
Source File: PBKDF2TranslateTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate a PBKDF2 secret key using given algorithm.
 */
private SecretKey getSecretKeyForPBKDF2(String algoDeriveKey, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoDeriveKey);
    PBEKeySpec spec = new PBEKeySpec(PASS_PHRASE.toCharArray(), salt,
            ITERATION_COUNT, KEY_SIZE);

    return skf.generateSecret(spec);
}
 
Example 12
Source File: DefaultAppLock.java    From narrate-android with Apache License 2.0 5 votes vote down vote up
private String decryptPassword(String encryptedPwd) {
    try {
        DESKeySpec keySpec = new DESKeySpec(BuildConfig.PASSWORD_ENC_SECRET.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] encryptedWithoutB64 = Base64.decode(encryptedPwd, Base64.DEFAULT);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64);
        return new String(plainTextPwdBytes);
    } catch (Exception e) {
    }
    return encryptedPwd;
}
 
Example 13
Source File: PBMacBuffer.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get SecretKey for the given PBKDF2 algorithm.
 *
 * @param thePBKDF2Algorithm - PBKDF2 algorithm
 * @return SecretKey according to thePBKDF2Algorithm
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
protected SecretKey getSecretKey(String thePBKDF2Algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Prepare salt
    byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation
    new SecureRandom().nextBytes(salt);

    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(
            "A #pwd# implied to be hidden!".toCharArray(),
            salt, 1000, 128);
    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(thePBKDF2Algorithm);
    return keyFactory.generateSecret(pbeKeySpec);
}
 
Example 14
Source File: SecurePasswordEncryption.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String encryptPassword( final String password, final String key )
  throws GeneralSecurityException, UnsupportedEncodingException {
  final SecretKeyFactory factory = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA1" );
  final KeySpec spec = new PBEKeySpec( key.toCharArray(), SALT, 1024, 128 );
  final SecretKey tmp = factory.generateSecret( spec );
  final SecretKey secret = new SecretKeySpec( tmp.getEncoded(), "AES" );
  return encryptPassword( password, secret, "AES/CBC/PKCS5PADDING" );
}
 
Example 15
Source File: AesDkCrypto.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] PBKDF2(char[] secret, byte[] salt,
    int count, int keyLength) throws GeneralSecurityException {

    PBEKeySpec keySpec = new PBEKeySpec(secret, salt, count, keyLength);
    SecretKeyFactory skf =
            SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = skf.generateSecret(keySpec);
    byte[] result = key.getEncoded();

    return result;
}
 
Example 16
Source File: Cryptos.java    From offspring with MIT License 5 votes vote down vote up
private static SecretKeySpec getKey(String passphrase)
    throws NoSuchAlgorithmException, InvalidKeySpecException,
    UnsupportedEncodingException {
  byte[] salt = makeSHA1Hash(
      passphrase + "my wehuifhwufhwfuihfiuehfsalt" + passphrase).getBytes(
      Config.offspring_charset);

  int iterations = 10000;
  SecretKeyFactory factory = SecretKeyFactory
      .getInstance("PBKDF2WithHmacSHA1");
  SecretKey tmp = factory.generateSecret(new PBEKeySpec(passphrase
      .toCharArray(), salt, iterations, 128));
  return new SecretKeySpec(tmp.getEncoded(), "AES");
}
 
Example 17
Source File: SSOSymmetrical.java    From kisso with Apache License 2.0 5 votes vote down vote up
/**
 * generate KEY
 */
private Key toKey(Algorithm algorithm, String strKey) throws Exception {
    /*
     * MD5 处理密钥
     */
    byte[] key = MD5.md5Raw(strKey.getBytes(SSOConfig.getSSOEncoding()));
    if (Algorithm.DES == algorithm) {
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm.getKey());
        SecretKey secretKey = keyFactory.generateSecret(dks);
        return secretKey;
    }
    return new SecretKeySpec(key, algorithm.getKey());
}
 
Example 18
Source File: ObscuredSharedPreferences.java    From android with GNU General Public License v3.0 5 votes vote down vote up
protected String encrypt(String value) {

        try {
            final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(), Settings.System.ANDROID_ID).getBytes(UTF8), 20));
            return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
 
Example 19
Source File: PKCS12SameKeyId.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }
 
Example 20
Source File: SecurePreferences.java    From Amphitheatre with Apache License 2.0 4 votes vote down vote up
/**
 * Derive a secure key based on the passphraseOrPin
 * 
 * @param passphraseOrPin
 * @param salt
 * @param algorthm
 *            - which PBE algorthm to use. some <4.0 devices don;t support
 *            the prefered PBKDF2WithHmacSHA1
 * @param iterations
 *            - Number of PBKDF2 hardening rounds to use. Larger values
 *            increase computation time (a good thing), defaults to 1000 if
 *            not set.
 * @param keyLength
 * @return Derived Secretkey
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.spec.InvalidKeySpecException
 * @throws java.security.NoSuchProviderException
 */
private static SecretKey generatePBEKey(char[] passphraseOrPin,
		byte[] salt, String algorthm, int iterations, int keyLength)
		throws NoSuchAlgorithmException, InvalidKeySpecException,
		NoSuchProviderException {

	if (iterations == 0) {
		iterations = 1000;
	}

	SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(
			algorthm, PROVIDER);
	KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations,
			keyLength);
	SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
	return secretKey;
}