Example usage for javax.crypto SecretKeyFactory getInstance

List of usage examples for javax.crypto SecretKeyFactory getInstance

Introduction

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

Prototype

public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecretKeyFactory object that converts secret keys of the specified algorithm.

Usage

From source file:om.edu.squ.squportal.portlet.dps.security.CryptoAES.java

/**
* 
* method name  : generateKey/*from w w  w .  j  av a  2  s.  c  om*/
* @param salt
* @param passphrase
* @return
* CryptoAES
* return type  : SecretKey
* 
* purpose      :
*
* Date          :   Nov 15, 2017 7:30:08 PM
*/
private SecretKey generateKey(String salt, String passphrase) {
    SecretKey secretKey = null;
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), hex(salt), iterationCount, keySize);
        SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
        secretKey = key;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        logger.error(":: Crypto Error :: Error in key generation : {}", e.getMessage());
    }
    return secretKey;
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException/*  w ww. j a  v a  2  s.  co m*/
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware.
    // see here:
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}

From source file:com.ethercamp.harmony.keystore.KeystoreFormat.java

private byte[] hash(String encryptedData, byte[] salt, int iterations) throws Exception {
    char[] chars = encryptedData.toCharArray();
    PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 256);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    return skf.generateSecret(spec).getEncoded();
}

From source file:com.ubipass.middleware.ems.EMSUtil.java

/**
 * set all licence parameters/*www . j  a  va 2s . c om*/
 * 
 * @throws Exception
 */
private static void setParameters() throws Exception {

    File file = new File(path + LICENCE_FILE);
    FileInputStream is;

    try {
        is = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        throw new InvalidLicenseException();
    }

    Properties properties = new Properties();
    properties.load(is);

    userName = properties.getProperty("userName");
    licenceKey = properties.getProperty("licenceKey");

    if (userName == null || licenceKey == null) {
        throw new InvalidLicenseException();
    }

    // DES????
    SecureRandom sr = new SecureRandom();

    byte rawKeyData[] = (userName + "midware").getBytes();

    // ?DESKeySpec
    DESKeySpec dks = new DESKeySpec(rawKeyData);

    // ?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);

    // ??
    licenceKey = new String(cipher.doFinal(Base64.decodeBase64(licenceKey.getBytes())));

    String tmpStr[] = licenceKey.split("-");

    if (tmpStr.length != 2)
        throw new InvalidLicenseException();

    licenceUser = tmpStr[0];
    licenceExpDate = tmpStr[1];

}

From source file:org.coronastreet.gpxconverter.AccountManager.java

public static String decrypt(String property) throws GeneralSecurityException, IOException {
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
    return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
}

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

private byte[] getHashedPassword(CryptoWrapperBuilder builder)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    /* Apply PBKDF2 (Password-Based Key Derivation Function 2) with
     * HMAC-SHA-1 to the password (for further details, see RFC-2898).
     *//*from   w w  w .  j  av a2s . c  o m*/
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(builder.password.toCharArray(), salt, keyDerivationIterationCount,
            builder.keySize);
    SecretKey secret = factory.generateSecret(spec);
    return secret.getEncoded();
}

From source file:com.meltmedia.jackson.crypto.EncryptionService.java

/**
 * Performs PBKDF2WithHmacSHA1 key stretching on password and returns a key of the specified length.
 * /*from  w w w .jav  a 2  s.  c  o m*/
 * @param password the clear text password to base the key on.
 * @param salt the salt to add to the password
 * @param iterationCount the number of iterations used when stretching
 * @param keyLength the length of the resulting key in bits
 * @return the stretched key
 * @throws NoSuchAlgorithmException if PBKDF2WithHmacSHA1 is not available
 * @throws InvalidKeySpecException if the specification of the key is invalid.
 */
static SecretKey stretchKey(char[] password, byte[] salt, int iterationCount, int keyLength)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password, salt, iterationCount, keyLength);
    return factory.generateSecret(spec);
}

From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java

/**
 * Key derivation method from the given password
 * @param password password to derive// w w w. j a va  2  s .c  o  m
 */
private void derivateKey(char[] password) {
    //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption
    SecretKeyFactory factory;
    try {
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        //1000 iteration should be enough since the attack has to be done online and
        //salt changes for each group
        KeySpec spec = new PBEKeySpec(password, this.salt, 1000, 256);
        SecretKey tmp = factory.generateSecret(spec);
        secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
        this.isReady = true;
    } catch (NoSuchAlgorithmException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
    }

}

From source file:org.apache.spark.network.crypto.AuthEngine.java

private SecretKeySpec generateKey(String kdf, int iterations, byte[] salt, int keyLength)
        throws GeneralSecurityException {

    SecretKeyFactory factory = SecretKeyFactory.getInstance(kdf);
    PBEKeySpec spec = new PBEKeySpec(secret, salt, iterations, keyLength);

    long start = System.nanoTime();
    SecretKey key = factory.generateSecret(spec);
    long end = System.nanoTime();

    LOG.debug("Generated key with {} iterations in {} us.", conf.keyFactoryIterations(), (end - start) / 1000);

    return new SecretKeySpec(key.getEncoded(), conf.keyAlgorithm());
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility
 * is required but encryption (obfuscation, technically) is required.
 *
 * @param value - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory
 * @param iterations - The number of times to loop through the keyspec
 * @param keyBits - The size of the key, in bits
 * @param algorithm - The algorithm to encrypt the data with
 * @param cipherInstance - The cipher instance to utilize
 * @param encoding - The text encoding//from   www  .  j av a  2 s  .  c o m
 * @return The encrypted string in a reversible format
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String decryptText(final String value, final String salt, final String secretInstance,
        final int iterations, final int keyBits, final String algorithm, final String cipherInstance,
        final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", secretInstance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", keyBits);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", cipherInstance);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String decPass = null;

    try {
        String decoded = new String(Base64.getDecoder().decode(value));
        String iv = decoded.split(":")[0];
        String property = decoded.split(":")[1];

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance);
        PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm);

        Cipher pbeCipher = Cipher.getInstance(cipherInstance);
        pbeCipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(Base64.getDecoder().decode(iv)));
        decPass = new String(pbeCipher.doFinal(Base64.getDecoder().decode(property)), encoding);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (NoSuchPaddingException npx) {
        throw new SecurityException(npx.getMessage(), npx);
    } catch (IllegalBlockSizeException ibx) {
        throw new SecurityException(ibx.getMessage(), ibx);
    } catch (BadPaddingException bpx) {
        throw new SecurityException(bpx.getMessage(), bpx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    } catch (InvalidAlgorithmParameterException iapx) {
        throw new SecurityException(iapx.getMessage(), iapx);
    } catch (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    }

    return decPass;
}