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.beligum.core.accounts.UserManager.java

private static String hash(String password, String salt) {
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 2048, 160);
    try {//  w  w w  .j  a v  a 2 s . c  o m
        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = f.generateSecret(spec).getEncoded();
        return new String(Hex.encodeHex(hash));
    } catch (Exception e) {
        return null;
    }

}

From source file:com.waveerp.desEncryption.java

public void Encrypter(String keyString, String ivString) {
    try {//from w  ww  . jav  a2s .c  o m

        keyString = "J3SuSChRiSt";
        ivString = "Pr0V3rBs";

        final MessageDigest msgDigest = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = msgDigest.digest(Base64.decodeBase64(keyString.getBytes("utf-8")));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        kSpec = new DESedeKeySpec(keyBytes);

        sKey = SecretKeyFactory.getInstance("DESede").generateSecret(kSpec);

        ivParSpec = new IvParameterSpec(ivString.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:tds.itemrenderer.security.Encryption.java

/**
 * initializes ciphers and adds jce provider if provided
 *
 * @throws TDS.Shared.Security.TDSEncryptionException
 *//*  w w  w .  j av a2  s  . c o  m*/
@PostConstruct
protected void init() {
    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));
    }

    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);
        encryptCipher = Cipher.getInstance(TRANSFORMATION);
        decryptCipher = Cipher.getInstance(TRANSFORMATION);
        encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
    } catch (NoSuchAlgorithmException e) {
        log.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Algorithm is not available");
    } catch (InvalidKeySpecException e) {
        log.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Key specification is not valid");
    } catch (NoSuchPaddingException e) {
        log.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Padding is not valid");
    } catch (InvalidKeyException e) {
        log.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Key is not valid");
    }
}

From source file:components.security.Password.java

/**
 * Hashes the password using pbkdf2 and the given salt.
 *
 * @param password the plain text password to hash.
 * @param salt     the salt for the password
 * @return the hashed password//ww  w  .  ja v  a  2s  .  co  m
 */
public char[] hash(char[] password, byte[] salt) {
    checkNotNull(password);
    checkArgument(password.length != 0);
    checkNotNull(salt);
    checkArgument(salt.length != 0);

    try {
        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey key = f.generateSecret(new PBEKeySpec(password, salt, iterations, desiredKeyLenght));
        return Base64.encodeBase64String(key.getEncoded()).toCharArray();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        Logger.error("Problem during password hashing", e);
        throw new IllegalStateException("Could not hash the password of the user.", e);
    }
}

From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java

/**
 * Method to initialize the cipher object with the correct encryption algorithm.
 *
 * @throws Exception//from ww w. jav  a  2s . c  o  m
 */
protected void initializeCipher() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY);
    KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
    SecretKey tmp = factory.generateSecret(spec);

    if (log.isDebugEnabled())
        log.debug("Secret Key Length: " + tmp.getEncoded().length);

    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC);

    cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION);
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector));
}

From source file:TripleDES.java

/** Save the specified TripleDES SecretKey to the specified file */
public static void writeKey(SecretKey key, File f)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Convert the secret key to an array of bytes like this
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec keyspec = (DESedeKeySpec) keyfactory.getKeySpec(key, DESedeKeySpec.class);
    byte[] rawkey = keyspec.getKey();

    // Write the raw key to the file
    FileOutputStream out = new FileOutputStream(f);
    out.write(rawkey);/*from ww w. jav a  2s. co m*/
    out.close();
}

From source file:com.adeptj.modules.security.jwt.internal.JwtKeys.java

static PrivateKey createSigningKey(JwtConfig jwtConfig, SignatureAlgorithm signatureAlgo) {
    LOGGER.info("Creating RSA signing key!!");
    String keyData = jwtConfig.privateKey();
    Assert.isTrue(StringUtils.startsWithAny(keyData, PRIVATE_ENCRYPTED_KEY_HEADER, PRIVATE_KEY_HEADER),
            INVALID_PRIVATE_KEY_MSG);//from ww w.j  av  a2s  . c o  m
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgo.getFamilyName());
        if (StringUtils.startsWith(keyData, PRIVATE_ENCRYPTED_KEY_HEADER)) {
            LOGGER.info("Creating PKCS8EncodedKeySpec from private [encrypted] key !!");
            Assert.hasText(jwtConfig.privateKeyPassword(), KEYPASS_NULL_MSG);
            byte[] privateKeyData = decodePrivateKeyData(keyData, true);
            EncryptedPrivateKeyInfo privateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyData);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(privateKeyInfo.getAlgName());
            PBEKeySpec keySpec = new PBEKeySpec(jwtConfig.privateKeyPassword().toCharArray());
            SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(privateKeyInfo.getAlgName());
            cipher.init(DECRYPT_MODE, secretKey, privateKeyInfo.getAlgParameters());
            return keyFactory.generatePrivate(privateKeyInfo.getKeySpec(cipher));
        }
        LOGGER.info("Creating PKCS8EncodedKeySpec from private key !!");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodePrivateKeyData(keyData, false)));
    } catch (GeneralSecurityException | IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new KeyInitializationException(ex.getMessage(), ex);
    }
}

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   w  w w  . j  a  v  a 2  s.c om
 * @return The encrypted string in a reversible format
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String 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 {
    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 encPass = null;

    try {
        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.ENCRYPT_MODE, sks);

        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);

        byte[] cryptoText = pbeCipher.doFinal(value.getBytes(encoding));
        byte[] iv = ivParameterSpec.getIV();

        String combined = Base64.getEncoder().encodeToString(iv) + ":"
                + Base64.getEncoder().encodeToString(cryptoText);

        encPass = Base64.getEncoder().encodeToString(combined.getBytes());
    } 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 (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    } catch (InvalidParameterSpecException ipsx) {
        throw new SecurityException(ipsx.getMessage(), ipsx);
    }

    return encPass;
}

From source file:com.adeptj.modules.commons.crypto.internal.HashingServiceImpl.java

@Override
public byte[] getHashedBytes(char[] plainText, byte[] salt) {
    Validate.isTrue(ArrayUtils.isNotEmpty(plainText), "plainText array can't be empty!!");
    Validate.isTrue(ArrayUtils.isNotEmpty(salt), "salt array can't be empty!!");
    try {//from   w  w  w  . ja  v a2 s  . com
        return SecretKeyFactory.getInstance(this.secretKeyAlgo)
                .generateSecret(new PBEKeySpec(plainText, salt, this.iterationCount, this.keyLength))
                .getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        LOGGER.error("Exception while generating hashed bytes!!", ex);
        throw new CryptoException(ex);
    }
}

From source file:com.redsqirl.workflow.utils.FileStream.java

private static SecretKey generateKey() throws Exception {
    PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt, iterations, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    return keyFactory.generateSecret(keySpec);
}