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

private static PKCS8EncodedKeySpec decryptPrivateKey(byte[] encryptedPrivateKey)
        throws GeneralSecurityException {
    EncryptedPrivateKeyInfo epkInfo;
    try {//from  ww  w  .ja  va  2s  . c o m
        epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
    } catch (IOException ex) {
        // Probably not an encrypted key.
        return null;
    }

    char[] password = System.console().readPassword("Password for the private key file: ");

    SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    Key key = skFactory.generateSecret(new PBEKeySpec(password));
    Arrays.fill(password, '\0');

    Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());

    try {
        return epkInfo.getKeySpec(cipher);
    } catch (InvalidKeySpecException ex) {
        System.err.println("Password may be bad.");
        throw ex;
    }
}

From source file:de.fhdo.helper.DES.java

public static String encrypt(String Text) {
    try {//from   www . j ava  2 s  . c  om
        DESKeySpec keySpec = new DESKeySpec("schluessel_stdrepository15".getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        // ENCODE plainTextPassword String
        byte[] cleartext = Text.getBytes("UTF8");
        Cipher cipher = Cipher.getInstance("DES");
        // cipher is not thread safe
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBase64URLSafeString(cipher.doFinal(cleartext));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:de.fhdo.helper.DES.java

public static String decrypt(String Text) {
    try {/*w w w.j  av  a  2 s  . c  o m*/
        DESKeySpec keySpec = new DESKeySpec("schluessel_stdrepository15".getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] encrypedPwdBytes = Base64.decodeBase64(Text);
        Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

        return new String(plainTextPwdBytes);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:org.apache.xml.security.samples.encryption.Decrypter.java

private static SecretKey loadKeyEncryptionKey() throws Exception {

    String fileName = "kek";
    String jceAlgorithmName = "DESede";

    File kekFile = new File(fileName);

    DESedeKeySpec keySpec = new DESedeKeySpec(JavaUtils.getBytesFromFile(fileName));
    SecretKeyFactory skf = SecretKeyFactory.getInstance(jceAlgorithmName);
    SecretKey key = skf.generateSecret(keySpec);

    System.out.println("Key encryption key loaded from " + kekFile.toURL().toString());
    return key;//w w w  .j av a2s .  c o  m
}

From source file:Encrypt.java

private static String encrypt(String message) throws Exception {
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
    IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}

From source file:Main.java

public static String encryptData(String password, String plaintextData) throws Exception {
    // Thank you Mr. Nelenkov
    String maybeThisHelps = "http://nelenkov.blogspot.com/2012/04/using-password-based-encryption-on.html";
    Log.v(TAG, maybeThisHelps);//from   w  w  w .  j a  v a2  s  . c  o  m
    int iterationCount = 100; //because Polaroid
    int keyLength = 256;
    int saltLength = keyLength;

    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[saltLength];
    random.nextBytes(salt);
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] iv = new byte[cipher.getBlockSize()];
    random.nextBytes(iv);

    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
    byte[] ciphertext = cipher.doFinal(plaintextData.getBytes("UTF-8"));

    String ivToString = new String(Base64.encode(iv, 0));
    String saltToString = new String(Base64.encode(salt, 0));
    String ciphertextToString = new String(Base64.encode(ciphertext, 0));

    Log.d(TAG, ivToString + "]" + saltToString + "]" + ciphertextToString);
    return (ivToString + "]" + saltToString + "]" + ciphertextToString).replace("\n", "");
}

From source file:Encrypt.java

private static String decrypt(String message) throws Exception {
    byte[] bytesrc = convertHexString(message);
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
    IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

    cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
    byte[] retByte = cipher.doFinal(bytesrc);
    return new String(retByte);
}

From source file:com.agiletec.aps.util.DefaultApsEncrypter.java

public static Key getKey() {
    try {//from w ww . j av a 2 s.  c  o  m
        byte[] bytes = KEY_STRING.getBytes();
        DESedeKeySpec pass = new DESedeKeySpec(bytes);
        SecretKeyFactory skf = SecretKeyFactory.getInstance(TRIPLE_DES_KEY_SPEC);
        SecretKey s = skf.generateSecret(pass);
        return s;
    } catch (Throwable t) {
        throw new RuntimeException("Error creating key", t);
    }
}

From source file:com.cisco.oss.foundation.directory.utils.ObfuscatUtil.java

/**
 * Encrypt the password in PBKDF2 algorithm.
 *
 * @param password//www  . j ava 2  s.c  o m
 *         the password to obfuscate.
 * @param salt
 *         the randomly sequence of bits of the user.
 * @return
 *         the obfuscated password byte array.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static byte[] pBKDF2ObfuscatePassword(String password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    String algorithm = "PBKDF2WithHmacSHA1";
    int derivedKeyLength = 160;
    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:com.ro.ssc.app.client.licensing.TrialKeyValidator.java

public static String decodeKey(String encodedEncrypted) {
    String decoded = "";
    try {/* w  w  w  .  j av a2 s.  c om*/
        byte[] saltDecrypt = SALT_DECRYPT.getBytes(StandardCharsets.UTF_8);
        SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
        SecretKey tmp2 = factoryKeyDecrypt.generateSecret(
                new PBEKeySpec(PASS_DECRYPT.toCharArray(), saltDecrypt, ITERATIONS_DECRYPT, KEY_LENGTH));
        SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), ALGORITHM);
        Cipher aesCipherDecrypt = Cipher.getInstance(CIPHER);
        aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
        byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
        byte[] eBytes = Base64.decodeBase64(e64bytes);
        byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
        decoded = StringUtils.newStringUtf8(cipherDecode);
    } catch (Exception e) {
        LOGGER.error("Error while decoding the trial key", e);
    }
    return decoded;
}