Example usage for javax.crypto.spec PBEKeySpec PBEKeySpec

List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec PBEKeySpec PBEKeySpec.

Prototype

public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength) 

Source Link

Document

Constructor that takes a password, salt, iteration count, and to-be-derived key length for generating PBEKey of variable-key-size PBE ciphers.

Usage

From source file:com.connorbrezinsky.msg.security.Hash.java

private static String hash(String password, byte[] salt) throws Exception {
    if (password == null || password.length() == 0)
        throw new IllegalArgumentException("Empty passwords are not supported.");
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
    return Base64.encodeBase64String(key.getEncoded());
}

From source file:com.ro.ssc.app.client.licensing.TrialKeyGenerator.java

public static String generateKey(String toEncode) {

    String encoded = "";
    try {/*  w  w w . jav a 2s  . c  om*/
        byte[] saltEncrypt = SALT_ENCRYPT.getBytes();
        SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
        SecretKey tmp = factoryKeyEncrypt.generateSecret(
                new PBEKeySpec(PASS_ENCRYPT.toCharArray(), saltEncrypt, ITERATIONS_ENCRYPT, KEY_LENGTH));
        SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);
        Cipher aesCipherEncrypt = Cipher.getInstance(CIPHER);
        aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
        byte[] bytes = StringUtils.getBytesUtf8(toEncode);
        byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
        encoded = Base64.encodeBase64URLSafeString(encryptBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encoded;
}

From source file:com.hurence.logisland.util.string.Anonymizer.java

public String anonymize(String str) throws NoSuchAlgorithmException, InvalidKeySpecException {

    // Hash the password
    PBEKeySpec spec = new PBEKeySpec(str.toCharArray(), salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
    byte[] hash = skf.generateSecret(spec).getEncoded();

    return Hex.encodeHexString(hash);
}

From source file:org.matrix.security.crypto.encrypt.AesBytesEncryptor.java

public AesBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator) {
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), Hex.decode(salt), 1024, 256);
    SecretKey secretKey = newSecretKey("PBKDF2WithHmacSHA1", keySpec);
    this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES");
    encryptor = newCipher(AES_ALGORITHM);
    decryptor = newCipher(AES_ALGORITHM);
    this.ivGenerator = ivGenerator != null ? ivGenerator : NULL_IV_GENERATOR;
}

From source file:CipherProvider.java

/**
 * Create cipher for encrypt or decrypt backup content
 *
 * @param passwd passwd for encryption/*from  www.j a  v  a2s  . c o  m*/
 * @param mode   encrypt/decrypt mode
 *
 * @return instance of cipher
 */
private static Cipher getCipher(final String passwd, final int mode) {
    /* Derive the key, given password and salt. */
    Cipher cipher = null;
    try {
        SecretKeyFactory factory = null;
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        String salt = "slNadZlato#%^^&(&(5?@#5166?1561?#%^^*^&54431"; // only pseudorandom salt
        KeySpec spec = new PBEKeySpec(passwd.toCharArray(), salt.getBytes(), 65536, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), CIPHER_TYPE);

        // initialization vector
        byte[] iv = Arrays.copyOfRange(DigestUtils.md5(passwd), 0, 16);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

        // Cipher for encryption
        cipher = Cipher.getInstance(CIPHER_TYPE + "/CBC/PKCS5Padding");
        cipher.init(mode, secret, paramSpec);
    } catch (Exception e) {
        e.printStackTrace(); //Todo implementovat
    }
    return cipher;
}

From source file:net.thewaffleshop.nimbus.api.EncryptionAPI.java

/**
 * Generate a {@link SecretKey} from a password and salt
 *
 * @param password//from   w  w  w  .j a v  a  2 s. co m
 * @param salt
 * @return
 */
public SecretKey createSecretKey(String password, byte[] salt) {
    try {
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 1024, 256);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey secretKey = factory.generateSecret(keySpec);
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gvmax.common.util.Enc.java

public Enc(String password, int keyLength) {
    if (password == null || password.trim().equals("")) {
        enabled = false;/*  www. j  a v  a  2  s .c  om*/
    } else {
        enabled = true;
        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1024, keyLength);
            key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
            c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

From source file:adminpassword.AESDemo.java

@SuppressWarnings("static-access")
public String decrypt(String encryptedText) throws Exception {

    byte[] saltBytes = salt.getBytes("UTF-8");
    byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    // Decrypt the message
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));

    byte[] decryptedTextBytes = null;
    try {//from w  ww  .j  a v a2s. c o m
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return new String(decryptedTextBytes);
}

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

@Test
void hashToken_shouldHashTheProvidedString() throws Exception {
    AccessToken.AccessTokenWithDisplayValue token = AccessToken.create(null, null, null, new TestingClock());

    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
            .generateSecret(new PBEKeySpec(token.getDisplayValue().substring(8).toCharArray(),
                    token.getSaltValue().getBytes(StandardCharsets.UTF_8), 4096, 256));

    assertThat(token.getValue()).isEqualTo(Hex.encodeHexString(key.getEncoded()));
}

From source file:Util.PassGen.java

private String hash(String password, byte[] salt) throws Exception {
    if (password == null || password.length() == 0) {
        throw new IllegalArgumentException("Empty passwords are not supported.");
    }/* w  ww  .  j  a v a 2 s .c om*/
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
    return Base64.encodeBase64String(key.getEncoded());
}