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

public static String deCrypto(String txt, String key) {
    SecretKeyFactory skeyFactory = null;
    Cipher cipher = null;/*  w  w  w  .j a  v a2 s. co m*/
    byte[] btxts = null;
    try {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
        skeyFactory = SecretKeyFactory.getInstance("DES");
        cipher = Cipher.getInstance("DES");
        SecretKey deskey = skeyFactory.generateSecret(desKeySpec);
        cipher.init(Cipher.DECRYPT_MODE, deskey);
        btxts = new byte[txt.length() / 2];
        for (int i = 0, count = txt.length(); i < count; i += 2) {
            btxts[i / 2] = (byte) Integer.parseInt(txt.substring(i, i + 2), 16);
        }
        return (new String(cipher.doFinal(btxts)));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;

}

From source file:org.artifactory.security.CryptoHelper.java

public static SecretKey generatePbeKey(String password) {
    try {/*from  w w w. ja v a2  s . co m*/
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SYM_ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(pbeKeySpec);
        return secretKey;
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("No such algorithm: " + e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("Unexpected exception: ", e);
    }
}

From source file:org.acegisecurity.util.EncryptionUtils.java

private static byte[] cipher(String key, byte[] passedBytes, int cipherMode) throws EncryptionException {
    try {/*from  w  ww  . java 2  s .c  o m*/
        final KeySpec keySpec = new DESedeKeySpec(stringToByteArray(key));
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        final SecretKey secretKey = keyFactory.generateSecret(keySpec);
        cipher.init(cipherMode, secretKey);
        return cipher.doFinal(passedBytes);
    } catch (final Exception e) {
        throw new EncryptionException(e.getMessage(), e);
    }
}

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  w ww. j  a  v a2  s .  c om
    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.dc.tes.License.java

public static byte[] decrypt(byte[] src, byte[] key) throws Exception {

    // DES????//from   w ww .j a  v a  2s .c o  m

    SecureRandom sr = new SecureRandom();

    // ?DESKeySpec

    DESKeySpec dks = new DESKeySpec(key);

    // ?DESKeySpec??

    // SecretKey

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

    SecretKey securekey = keyFactory.generateSecret(dks);

    // Cipher??

    Cipher cipher = Cipher.getInstance("DES");

    // Cipher

    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

    // ??

    // ??

    return cipher.doFinal(src);

}

From source file:egovframework.com.ext.jfile.security.service.CipherServiceImpl.java

/**
 *   ?.// w w  w .  j a  v  a2s  .  c  o m
 * @param keyAlgorithm  .
 * @param algorithm .
 * @param keyData  ??.
 * @return Key  .
 * @throws NoSuchAlgorithmException   ?  ?  .
 * @throws InvalidKeyException  ? key ?  
 * @throws InvalidKeySpecException  ? keySpec ?  
 */
private static Key generateKey(String keyAlgorithm, String algorithm, byte[] keyData)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    if (keyAlgorithm == null || "".equals(keyAlgorithm))
        throw new NoSuchAlgorithmException("algorithm is nessary");
    String upper = keyAlgorithm.toUpperCase();
    if ("DES".equals(upper)) {
        KeySpec keySpec = new DESKeySpec(keyData);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(keyAlgorithm);

        SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
        return secretKey;

    } else if (upper.indexOf("DESEDE") > -1 || upper.indexOf("TRIPLEDES") > -1) {
        KeySpec keySpec = new DESedeKeySpec(keyData);

        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(keyAlgorithm);
        SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
        return secretKey;
    } else {
        SecretKeySpec keySpec = new SecretKeySpec(keyData, keyAlgorithm);
        return keySpec;
    }
}

From source file:edu.ku.brc.helpers.Encryption.java

/**
 * Decrypt the string from its array of bytes
 * @param input the actual string (in bytes) that is to be decrypted
 * @param password a password, which is really any string, but must be the same string that was used to encrypt it.
 * @return a byte array of the decrypted chars
 * @throws Exception in case something goes wrong
 *//*from   ww w  .  j a  v  a2s.  com*/
public static byte[] decrypt(final byte[] input, final char[] password) throws Exception {
    /*
     * The first SALT_LENGTH bytes of the input ciphertext are actually the salt, not the
     * ciphertext.
     */
    byte[] salt = new byte[SALT_LENGTH];
    System.arraycopy(input, 0, salt, 0, SALT_LENGTH);

    /*
     * We can now create a key from our salt (extracted just above), password, and iteration
     * count. Same procedure to create the key as in Encryption().
     */
    PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
    SecretKey key = skf.generateSecret(keyspec);

    /*
     * Once again, create a PBEParameterSpec object and a Cipher object.
     */
    PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT);
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, key, paramspec);

    /*
     * Decrypt the data. The parameters we pass into doFinal() instruct it to skip the first
     * SALT_LENGTH bytes of input (which are actually the salt), and then to Encryption the next
     * (length - SALT_LENGTH) bytes, which are the real ciphertext.
     */
    byte[] output = cipher.doFinal(input, SALT_LENGTH, input.length - SALT_LENGTH);

    /* Clear the password and return the generated plaintext. */
    keyspec.clearPassword();
    return output;
}

From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java

/**
 * Creates a key that can be used with a cryptographic service provider. The key is computed from
 * the specified password and protected with the specified salt. 
 * @param password the password from which the key is computed.
 * @param salt the salt that is used to protect the key from dictionary attacks.
 * @return a key that can be used with a cryptographic service provider.
 * @throws Exception if an error occurs in the execution of the operation.
 *//*from   w  ww .  ja v  a2s  .co m*/
public static SecretKey generateKey(final String password, final byte[] salt) throws Exception {
    SecretKey secret;
    if (UNLIMITED_CRYPTOGRAPHY_AVAILABLE) {
        // bouncycastle equivalent: SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC")
        final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        final PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
        secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    } else {
        // bouncycastle equivalent: SecretKeyFactory.getInstance("PBEWITHSHA256AND128BITAES-CBC-BC")
        final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        final PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
        secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
    }
    return secret;
}

From source file:eu.vital.vitalcep.collector.Collector.java

private 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(Base64.getDecoder().decode(property), StandardCharsets.UTF_8);
}