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:Crypto.java

/**
 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
 * and generates the salt bytes using secureRandom().  The encryption secret key is created 
 * along with the initialization vectory. The member variable mEcipher is created to be used
 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
 * to be written to disk./*  w  ww  .j a  v a2s. c om*/
 *  
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    // crate secureRandom salt and store  as member var for later use
    mSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(mSalt);
    Db("generated salt :" + Hex.encodeHexString(mSalt));

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /* 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
     */
    KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Create the Encryption cipher object and store as a member variable
     */
    mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    mEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = mEcipher.getParameters();

    // get the initialization vectory and store as member var 
    mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

    Db("mInitVec is :" + Hex.encodeHexString(mInitVec));
}

From source file:com.example.license.DESUtil.java

/**
 * ?/*from  w w w .ja  va2s.  c  o  m*/
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return ??
 */
public static String decryptBase64(String data, String key) throws Exception {
    DESKeySpec desKey = new DESKeySpec(key.getBytes());
    // ?DESKeySpec??
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
    SecretKey securekey = keyFactory.generateSecret(desKey);

    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, securekey);
    // ?
    return new String(cipher.doFinal(Base64.decodeBase64(data.getBytes())));
}

From source file:com.titilink.common.app.EncryptDecryptUtil.java

public void testDES() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
    ///*from   ww  w.j  a va  2s .co  m*/
    DESKeySpec desKeySpec = new DESKeySpec("SECURITY".getBytes(Charset.forName("UTF-8")));
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

    //??
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //?
    Cipher cipher1 = Cipher.getInstance("DES");
    cipher1.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));
}

From source file:TDS.Shared.Web.Encryption.java

/**
 * initializes ciphers and adds jce provider if provided
 * /*from   www.j ava2s  .c  om*/
 * @throws TDSEncryptionException
 */
@PostConstruct
protected void init() {
    final String encryptionKey = configurationManager.getAppSettings().get("EncryptionKey");

    if (encryptionKey == null || StringUtils.isBlank(encryptionKey)
            || encryptionKey.length() < MINIMUM_KEY_LENGTH) {
        throw new TDSEncryptionException(
                String.format("Number of characters for key must be greater than %s", MINIMUM_KEY_LENGTH));
    }

    if (_jceProvider != null) {
        try {
            Security.addProvider(((Provider) Class.forName(_jceProviderClass).newInstance()));
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            _logger.error(e.getMessage(), e);
            throw new TDSEncryptionException("JCE Provider class name is not valid");
        }
    }

    try {

        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBE_KEY_ALGORITHM);
        KeySpec keySpec = new PBEKeySpec(encryptionKey.toCharArray(), PBE_SALT, PBE_NUM_ITERATIONS,
                PBE_KEY_LENGTH);
        SecretKey secretKeyTemp;
        secretKeyTemp = secretKeyFactory.generateSecret(keySpec);
        _secretKey = new SecretKeySpec(secretKeyTemp.getEncoded(), CIPHER_ALGORITHM);
        if (_jceProvider == null) {
            _encryptCipher = Cipher.getInstance(TRANSFORMATION);
            _decryptCipher = Cipher.getInstance(TRANSFORMATION);
        } else {
            _encryptCipher = Cipher.getInstance(TRANSFORMATION, _jceProvider);
            _decryptCipher = Cipher.getInstance(TRANSFORMATION, _jceProvider);
        }
        _encryptCipher.init(Cipher.ENCRYPT_MODE, _secretKey);
    } catch (NoSuchAlgorithmException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Algorithm is not available");
    } catch (InvalidKeySpecException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Key specification is not valid");
    } catch (NoSuchPaddingException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Padding is not valid");
    } catch (NoSuchProviderException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Provider is not available");
    } catch (InvalidKeyException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Key is not valid");
    }
}

From source file:com.nextep.designer.core.services.impl.RepositoryService.java

public RepositoryService() {
    pbeParamSpec = new PBEParameterSpec(salt, iterations);
    pbeKeySpec = new PBEKeySpec(encryptionPassword.toCharArray());
    try {//from www. j  ava 2 s .  c  o m
        SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
        key = factory.generateSecret(pbeKeySpec);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(CoreMessages.getString("repositoryService.encryptionNotFound"), e); //$NON-NLS-1$
    } catch (InvalidKeySpecException e) {
        LOGGER.error(CoreMessages.getString("repositoryService.encryptionKeyFail"), e); //$NON-NLS-1$
    }
}

From source file:com.thoughtworks.go.domain.AccessToken.java

static String digestToken(String originalToken, String salt) {
    try {/*from w  w  w  . ja v  a2s .  co  m*/
        ACCESS_TOKEN_LOGGER.debug(
                "Generating secret using algorithm: {} with spec: DEFAULT_ITERATIONS: {}, DESIRED_KEY_LENGTH: {}",
                KEY_ALGORITHM, DEFAULT_ITERATIONS, DESIRED_KEY_LENGTH);
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        SecretKey key = factory.generateSecret(new PBEKeySpec(originalToken.toCharArray(), salt.getBytes(),
                DEFAULT_ITERATIONS, DESIRED_KEY_LENGTH));
        return Hex.encodeHexString(key.getEncoded());
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.xdi.util.security.StringEncrypter.java

/**
 * Constructor specifying scheme and key
 * /*from  w w  w  .  ja  va  2  s  .  co m*/
 * @param encryptionScheme
 *            Encryption scheme to use
 * @param encryptionKey
 *            Encryption key to use
 * @throws EncryptionException
 */
public StringEncrypter(final String encryptionScheme) throws EncryptionException {
    try {
        keyFactory = SecretKeyFactory.getInstance(encryptionScheme);
        cipher = Cipher.getInstance(encryptionScheme);
    } catch (final NoSuchAlgorithmException e) {
        throw new EncryptionException(e);
    } catch (final NoSuchPaddingException e) {
        throw new EncryptionException(e);
    }
}

From source file:ropes.Crypto.java

/**
* this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
* and generates the salt bytes using secureRandom().  The encryption secret key is created 
* along with the initialization vectory. The member variable mEcipher is created to be used
* by the class later on when either creating a CipherOutputStream, or encrypting a buffer
* to be written to disk.//  w  w  w .  j  a  va 2 s  .co  m
*  
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidParameterSpecException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
*/
public void setupEncrypt() {
    try {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;

        // crate secureRandom salt and store  as member var for later use
        mSalt = new byte[SALT_LEN];
        SecureRandom rnd = new SecureRandom();
        rnd.nextBytes(mSalt);
        Db("generated salt :" + Hex.encodeHexString(mSalt));

        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        /* 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
        */
        KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);
        tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        /* Create the Encryption cipher object and store as a member variable
        */
        mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        mEcipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = mEcipher.getParameters();

        // get the initialization vectory and store as member var
        mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

        Db("mInitVec is :" + Hex.encodeHexString(mInitVec));
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidParameterSpecException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.cherong.mock.common.base.util.EncryptionUtil.java

/**
 * deskey//  w w w  . j a  v a 2s. c  o  m
 * 
 * @param content
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByDES(String content, String key) {
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey sk = skf.generateSecret(dks);
        Cipher cip = Cipher.getInstance(DES_CIPHER_ALGORITHM);
        cip.init(Cipher.ENCRYPT_MODE, sk);
        return cip.doFinal(content.getBytes());
    } catch (Exception e) {
        LOGGER.error("{}", e);
        return null;
    }

}

From source file:org.runway.utils.StringEncryptDecryptUtil.java

public static String decrypt(String value) throws RunwaySecurityException {
    String result = null;//from w ww. j a  va  2  s .c om
    SecretKeyFactory keyFactory;

    try {

        keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance(ALGORITHM);
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        result = new String(pbeCipher.doFinal(base64Decode(value)));

    } catch (NoSuchAlgorithmException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidKeySpecException e) {
        throw new RunwaySecurityException(e);
    } catch (NoSuchPaddingException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidKeyException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RunwaySecurityException(e);
    } catch (IllegalBlockSizeException e) {
        throw new RunwaySecurityException(e);
    } catch (BadPaddingException e) {
        throw new RunwaySecurityException(e);
    } catch (IOException e) {
        throw new RunwaySecurityException(e);
    }

    return result;
}