Example usage for javax.crypto SecretKeyFactory generateSecret

List of usage examples for javax.crypto SecretKeyFactory generateSecret

Introduction

In this page you can find the example usage for javax.crypto SecretKeyFactory generateSecret.

Prototype

public final SecretKey generateSecret(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a SecretKey object from the provided key specification (key material).

Usage

From source file:com.pdftron.pdf.utils.Utils.java

public static String decryptIt(Context context, String value) {
    String cryptoPass = context.getString(context.getApplicationInfo().labelRes);
    try {/*w  w  w.  j a  va  2s.com*/
        DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
        // cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));

        String decrypedValue = new String(decrypedValueBytes);
        Log.d("MiscUtils", "Decrypted: " + value + " -> " + decrypedValue);
        return decrypedValue;

    } catch (Exception e) {
        Log.e(e.getClass().getName(), e.getMessage());
    }
    return value;
}

From source file:org.cesecore.util.StringTools.java

public static String pbeDecryptStringWithSha256Aes192(final String in) throws IllegalBlockSizeException,
        BadPaddingException, InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchPaddingException, UnsupportedEncodingException {
    CryptoProviderTools.installBCProviderIfNotAvailable();
    if (CryptoProviderTools.isUsingExportableCryptography()) {
        log.warn("De-obfuscation not possible due to weak crypto policy.");
        return in;
    }//from w  ww  . j  a va 2  s .  co  m

    final String algorithm = "PBEWithSHA256And192BitAES-CBC-BC";
    final Cipher c = Cipher.getInstance(algorithm, "BC");
    final PBEKeySpec keySpec = new PBEKeySpec(p, getSalt(), iCount);
    final SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm, "BC");

    c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec));

    final byte[] dec = c.doFinal(Hex.decode(in.getBytes("UTF-8")));
    return new String(dec);
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Decrypt private key with symmetric AES encryption, GCM mode mode and no padding
 *
 * @param privateKey byte64 encoded string representation of private key, IV separated with "|"
 * @param keyPhrase  key used for encryption, e.g. 12 random words
 *                   {@link EncryptionUtils#getRandomWords(int, Context)}
 * @return decrypted string//  w ww . j a v  a  2 s  . co m
 */
public static String decryptPrivateKey(String privateKey, String keyPhrase)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException, InvalidAlgorithmParameterException {

    // split up iv, salt
    String[] strings = privateKey.split(ivDelimiter);
    String realPrivateKey = strings[0];
    byte[] iv = decodeStringToBase64Bytes(strings[1]);
    byte[] salt = decodeStringToBase64Bytes(strings[2]);

    Cipher cipher = Cipher.getInstance(AES_CIPHER);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES);

    cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));

    byte[] bytes = decodeStringToBase64Bytes(realPrivateKey);
    byte[] decrypted = cipher.doFinal(bytes);

    String pemKey = decodeBase64BytesToString(decrypted);

    return pemKey.replaceAll("\n", "").replace("-----BEGIN PRIVATE KEY-----", "")
            .replace("-----END PRIVATE KEY-----", "");
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Encrypt private key with symmetric AES encryption, GCM mode mode and no padding
 *
 * @param privateKey byte64 encoded string representation of private key
 * @param keyPhrase  key used for encryption, e.g. 12 random words
 *                   {@link EncryptionUtils#getRandomWords(int, Context)}
 * @return encrypted string, bytes first encoded base64, IV separated with "|", then to string
 *///from   w w w  .ja  va 2 s.c o m
public static String encryptPrivateKey(String privateKey, String keyPhrase)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException {
    Cipher cipher = Cipher.getInstance(AES_CIPHER);

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] salt = randomBytes(saltLength);
    KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES);

    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] bytes = encodeStringToBase64Bytes(privateKey);
    byte[] encrypted = cipher.doFinal(bytes);

    byte[] iv = cipher.getIV();
    String encodedIV = encodeBytesToBase64String(iv);
    String encodedSalt = encodeBytesToBase64String(salt);
    String encodedEncryptedBytes = encodeBytesToBase64String(encrypted);

    return encodedEncryptedBytes + ivDelimiter + encodedIV + ivDelimiter + encodedSalt;
}

From source file:com.titilink.camel.rest.util.PasswordUtils.java

/**
 * Rabiitsalt?AES????SHA256??.//from w w w.  ja  va2s.  c  o m
 *
 * @param Rabiit ??
 * @param salt   ?
 * @return 
 */
public synchronized static Key generateKey(char[] Rabiit, byte[] salt) {
    SecretKeyFactory factory;
    SecretKey tmpkey = null;
    SecretKey secret = null;
    try {
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        //AES128??AES128
        int aeskeylen = AppProperties.getAsInt("AES_KEY_LEN", AES_KEY_LEN);
        KeySpec keyspec = new PBEKeySpec(Rabiit, salt, ITERATION_COUNT, aeskeylen);
        tmpkey = factory.generateSecret(keyspec);

        //AES??
        secret = new SecretKeySpec(tmpkey.getEncoded(), ENCODER_AES);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error("generateKey error, no such method exception.");
    } // "PBKDF2WithHmacSHA256"   JDK8??
    catch (InvalidKeySpecException e) {
        LOGGER.error("generateKey error, invalid key exception.");
    }
    return secret;
}

From source file:org.owasp.webgoat.lessons.Encoding.java

/**
 * Convenience method for encrypting a string.
 * //from  ww  w . j  ava  2s . com
 * @param str
 *            Description of the Parameter
 * @param pw
 *            Description of the Parameter
 * @return String the encrypted string.
 */

public static synchronized String decryptString(String str, String pw) {

    try {

        PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);

        SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

        Cipher passwordDecryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");

        char[] pass = pw.toCharArray();

        SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));

        passwordDecryptCipher.init(Cipher.DECRYPT_MODE, k, ps);

        // byte[] dec = decoder.decodeBuffer(str);
        byte[] dec = Base64.decodeBase64(str);

        byte[] utf8 = passwordDecryptCipher.doFinal(dec);

        return new String(utf8, "UTF-8");
    }

    catch (Exception e) {

        return ("This is not an encrypted string");
    }

}

From source file:org.owasp.webgoat.lessons.Encoding.java

/**
 * Convenience method for encrypting a string.
 * /*from   w ww. java  2s  .  com*/
 * @param str
 *            Description of the Parameter
 * @param pw
 *            Description of the Parameter
 * @return String the encrypted string.
 * @exception SecurityException
 *                Description of the Exception
 */

public static synchronized String encryptString(String str, String pw) throws SecurityException {

    try {

        PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);

        SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

        Cipher passwordEncryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");

        char[] pass = pw.toCharArray();

        SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));

        passwordEncryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);

        byte[] utf8 = str.getBytes("UTF-8");

        byte[] enc = passwordEncryptCipher.doFinal(utf8);

        //return encoder.encode(enc);
        return Base64.encodeBase64String(enc);
    }

    catch (Exception e) {

        return ("Encryption error");
    }

}

From source file:com.hypersocket.auth.PasswordEncryptionService.java

public byte[] getEncryptedPassword(char[] password, byte[] salt, PasswordEncryptionType type)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    KeySpec spec = new PBEKeySpec(password, salt, type.getIterations(), type.getKeyLength());

    SecretKeyFactory f = SecretKeyFactory.getInstance(type.toString());

    return f.generateSecret(spec).getEncoded();
}

From source file:org.beangle.security.codec.DESEncrypt.java

public byte[] doEncrypt(byte plainText[]) throws Exception {
    SecureRandom sr = new SecureRandom();
    byte rawKeyData[] = desKey;
    DESKeySpec dks = new DESKeySpec(rawKeyData);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    javax.crypto.SecretKey key = keyFactory.generateSecret(dks);
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(1, key, sr);//from   w w w  .  jav a2 s.c om
    byte data[] = plainText;
    byte encryptedData[] = cipher.doFinal(data);
    return encryptedData;
}

From source file:net.sf.hajdbc.codec.crypto.CipherCodecTest.java

@Before
public void before() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
    Key key = factory.generateSecret(new DESKeySpec(Base64.decodeBase64(KEY.getBytes())));

    this.codec = new CipherCodec(key);
}