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:com.fegor.alfresco.security.crypto.Crypto.java

/**
 * Encryption configuration/*  ww w.  j a va 2s  . com*/
 * 
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void configEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    salt_pos = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(salt_pos);

    if (logger.isDebugEnabled())
        logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]");

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /*
     * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files
     * .shtml
     */
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    eCipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = eCipher.getParameters();

    vector_init = params.getParameterSpec(IvParameterSpec.class).getIV();

    if (logger.isDebugEnabled())
        logger.debug(
                this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]");
}

From source file:test.frames.CryptoServiceSingleton.java

/**
 * Generate the AES key from the salt and the private key.
 *
 * @param salt       the salt (hexadecimal)
 * @param privateKey the private key/*w ww .  ja  v a2s . com*/
 * @return the generated key.
 */
private SecretKey generateAESKey(String privateKey, String salt) {
    try {
        byte[] raw = Hex.decodeHex(salt.toCharArray());
        KeySpec spec = new PBEKeySpec(privateKey.toCharArray(), raw, iterationCount, keySize);
        SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF_2_WITH_HMAC_SHA_1);
        return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), AES_ECB_ALGORITHM);
    } catch (DecoderException e) {
        throw new IllegalStateException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalStateException(e);
    }
}

From source file:spacetraffic.kiv.zcu.cz.gameelement.MinigamePasswordHasher.java

/**
 * Method for generating key./*from   w w w .j a v a2 s. com*/
 * @return key
 * @throws Exception
 */
private Key generateKey() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
    char[] pdkbf2Password = PDKBF2_PASSWORD.toCharArray();
    byte[] salt = SALT.getBytes(CHARSET);

    KeySpec keySpec = new PBEKeySpec(pdkbf2Password, salt, 65536, 128);
    SecretKey secretKey = factory.generateSecret(keySpec);
    byte[] encodedKey = secretKey.getEncoded();

    return new SecretKeySpec(encodedKey, "AES");
}

From source file:eu.uqasar.service.AuthenticationService.java

/**
 *
 * @param password//from ww w. ja  va2  s .c  om
 * @param salt
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static byte[] getEncryptedPassword(String password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // PBKDF2 with SHA-1 as the hashing algorithm. Note that the NIST
    // specifically names SHA-1 as an acceptable hashing algorithm for
    // PBKDF2
    String algorithm = "PBKDF2WithHmacSHA1";
    // SHA-1 generates 160 bit hashes, so that's what makes sense here
    int derivedKeyLength = 160;
    // Pick an iteration count that works for you. The NIST recommends at
    // least 1,000 iterations:
    // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
    // iOS 4.x reportedly uses 10,000:
    // http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-passwords/
    int iterations = 20000;
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
    SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
    return f.generateSecret(spec).getEncoded();
}

From source file:org.yes.cart.web.support.util.cookie.impl.CookieTuplizerImpl.java

/**
 * Default Constructor.//w  w  w .  ja  va 2 s . co  m
 *
 * @param keyRingPassword      key ring password to use.
 * @param chunkSize            Base64 chunk size.
 * @param secretKeyFactoryName Secret Key Factory Name.
 * @param cipherName           Cipher name.
 */
public CookieTuplizerImpl(final String keyRingPassword, final int chunkSize, final String secretKeyFactoryName,
        final String cipherName) {

    this.chunkSize = chunkSize;

    try {
        final DESKeySpec desKeySpec = new DESKeySpec(keyRingPassword.getBytes());

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretKeyFactoryName);
        secretKey = keyFactory.generateSecret(desKeySpec);

        // Create Cipher
        desCipher = Cipher.getInstance(cipherName);
        desCipher.init(Cipher.ENCRYPT_MODE, secretKey);
        // create uncipher
        desUnCipher = Cipher.getInstance(cipherName);

        desUnCipher.init(Cipher.DECRYPT_MODE, secretKey);
    } catch (Exception ike) {
        ShopCodeContext.getLog(this).error(ike.getMessage(), ike);
        throw new RuntimeException("Unable to load Cipher for CookieTuplizer", ike);
    }

}

From source file:com.aurel.track.report.query.ReportQueryBL.java

private static String dcl(String encryptedText, char[] password) {
    byte[] clearText = { ' ' };
    int count = 20;
    PBEKeySpec pbeKeySpec;//from  w w w .  j  av  a 2  s .c o m
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    pbeKeySpec = new PBEKeySpec(password);
    try {
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] ciphertext = Base64.decodeBase64(encryptedText);

        // Decrypt the cleartext
        clearText = pbeCipher.doFinal(ciphertext);
    } catch (Exception e) {
    }
    return new String(clearText);
}

From source file:com.wms.studio.security.utils.Digests.java

public static byte[] desDecrypt(byte[] pwd, byte[] key) throws Exception {
    // ?DESKeySpec
    DESKeySpec dks = new DESKeySpec(key);
    // ?DESKeySpec??SecretKey
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher??//ww w  . j a v a2  s . c  om
    Cipher cipher = Cipher.getInstance(DES);
    // ?Cipher
    cipher.init(Cipher.DECRYPT_MODE, securekey, random);
    return cipher.doFinal(pwd);
}

From source file:com.aurel.track.admin.customize.category.filter.execute.ReportQueryBL.java

private static String dcl(String encryptedText, char[] password) {
    byte[] clearText = { ' ' };
    int count = 20;
    PBEKeySpec pbeKeySpec;/*from  w  ww. j a  v  a2 s  .co m*/
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    pbeKeySpec = new PBEKeySpec(password);
    try {
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] ciphertext = Base64.decodeBase64(encryptedText);

        //Decrypt the cleartext
        clearText = pbeCipher.doFinal(ciphertext);
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e), e);
    }
    return new String(clearText);
}

From source file:com.registryKit.user.userManager.java

public byte[] getEncryptedPassword(String password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    // PBKDF2 with SHA-1 as the hashing algorithm. Note that the NIST
    // specifically names SHA-1 as an acceptable hashing algorithm for PBKDF2
    String algorithm = "PBKDF2WithHmacSHA1";

    // SHA-1 generates 160 bit hashes, so that's what makes sense here
    int derivedKeyLength = 160;

    // Pick an iteration count that works for you. The NIST recommends at
    // least 1,000 iterations:
    // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
    // iOS 4.x reportedly uses 10,000:
    // http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-passwords/
    int iterations = 20000;

    // byte[] b = string.getBytes(Charset.forName("UTF-8"));
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);

    SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);

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

From source file:org.pentaho.mondrian.publish.PublishToServerCommand.java

public PublishToServerCommand() {
    try {/*ww w .  j a  v  a 2  s . co  m*/
        byte[] keyAsBytes = "abcdefghijkPENTAHOlmnopqrstuvw5xyz".getBytes("UTF8");
        KeySpec keySpec = new DESedeKeySpec(keyAsBytes);
        keyFactory = SecretKeyFactory.getInstance("DESede");
        encryptionKey = keyFactory.generateSecret(keySpec);
        cipher = Cipher.getInstance("DESede");
    } catch (Exception e) {
        LOG.severe("failed to initialize password encryption");
        e.printStackTrace();
    }
}