Example usage for org.bouncycastle.crypto PBEParametersGenerator PKCS12PasswordToBytes

List of usage examples for org.bouncycastle.crypto PBEParametersGenerator PKCS12PasswordToBytes

Introduction

In this page you can find the example usage for org.bouncycastle.crypto PBEParametersGenerator PKCS12PasswordToBytes.

Prototype

public static byte[] PKCS12PasswordToBytes(char[] password) 

Source Link

Document

converts a password to a byte array according to the scheme in PKCS12 (unicode, big endian, 2 zero pad bytes at the end).

Usage

From source file:GenTestDKs.java

License:Open Source License

private static void testKey(PKCS12ParametersGenerator pgen, int keyLen, int iterCount, String password,
        byte[] salt) {
    System.out.println("key len = " + keyLen + ", iter count = " + iterCount + ", password = \"" + password
            + "\", salt len = " + salt.length);

    char[] pwChars = password.toCharArray();
    byte[] pwBytes = PBEParametersGenerator.PKCS12PasswordToBytes(pwChars);

    pgen.init(pwBytes, salt, iterCount);
    KeyParameter kp = (KeyParameter) pgen.generateDerivedParameters(keyLen);
    printByteArray(kp.getKey());//from  w  ww.j  a  v a2  s.co  m
}

From source file:com.password.locker.crypto.SecureCryptoImpl.java

License:Open Source License

/**
 * SecureCrypto Constructor./*  ww w  . ja va2 s.co  m*/
 * 
 * @param password
 *       password for the crypto keyspec.
 * 
 * @throws InvalidAlgorithmParameterException 
 * @throws InvalidKeyException 
 * @throws NoSuchPaddingException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 */
public SecureCryptoImpl(final char[] password) throws InvalidKeyException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {

    SHA256Digest digest = new SHA256Digest();

    String s = Constants.PROPERTIES.getStringProperty(Constants.SALT_KEY, PasswordUtils.getSalt(digest));
    salt = Hex.decode(s);
    if (salt.length != digest.getDigestSize()) {
        LOGGER.warn("Warning salt size is not the size of the Digest.");
    }

    //---------------------------------------------------
    // Setup encryption.
    //---------------------------------------------------
    PBEParametersGenerator pGen = new PKCS12ParametersGenerator(digest);

    pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(password), salt, ITERATIONS);

    ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(KEY_LEN, IV_LEN);

    SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES");

    encryption = Cipher.getInstance(Constants.CRYPTO_ALGORITHM, new BouncyCastleProvider());

    encryption.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));

    //---------------------------------------------------
    // Setup decryption.
    //---------------------------------------------------

    decryption = Cipher.getInstance(Constants.CRYPTO_SEC_KEY_SPEC, new BouncyCastleProvider());

    PBEKeySpec keySpec = new PBEKeySpec(password, salt, ITERATIONS);
    SecretKeyFactory fact = SecretKeyFactory.getInstance(Constants.CRYPTO_SEC_KEY_SPEC,
            new BouncyCastleProvider());

    try {
        decryption.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec));
    } catch (InvalidKeySpecException e) {
        ExceptionUtils.fatalError(SecureCryptoImpl.class, e);
    }
    Constants.PROPERTIES.addProperty(Constants.SALT_KEY, s);
}

From source file:com.symbian.security.Pkcs12Pbe.java

License:Open Source License

private void getKey(int keyLen, int ivLen, int iterCount, String password, byte[] salt) {
    System.out.print("key len = " + keyLen + ", iter count = " + iterCount + ", password = \"" + password
            + "\", salt = ");
    printUnformattedByteArray(salt);//w w  w . java 2  s. c om

    char[] pwChars = password.toCharArray();
    byte[] pwBytes = PBEParametersGenerator.PKCS12PasswordToBytes(pwChars);

    pgen.init(pwBytes, salt, iterCount);
    CipherParameters cp = pgen.generateDerivedParameters(keyLen, ivLen);

    ParametersWithIV ivp = (ParametersWithIV) cp;
    KeyParameter kp = (KeyParameter) ivp.getParameters();

    System.out.print("key ");
    printUnformattedByteArray((kp.getKey()));
    System.out.print("iv ");
    printUnformattedByteArray(ivp.getIV());

    kp = (KeyParameter) pgen.generateDerivedMacParameters(160);
    System.out.print("160bit hmac key ");
    printUnformattedByteArray((kp.getKey()));

}

From source file:edu.vt.middleware.crypt.pbe.PKCS12KeyGenerator.java

License:Open Source License

/** {@inheritDoc} */
protected byte[] toBytes(final char[] password) {
    return PBEParametersGenerator.PKCS12PasswordToBytes(password);
}

From source file:edu.vt.middleware.crypt.PbeKeyGenerator.java

License:Open Source License

/**
 * Generate a key from a text password using the PKCS#12 method described at
 * http://www.rsa.com/rsalabs/node.asp?id=2138.
 *
 * @param  password  Raw material used for key generation.
 * @param  keyBitLength  Size of generated key in bits.
 * @param  digest  Digest algorithm to use during key generation.
 * @param  salt  Key initialization data.
 *
 * @return  Secret key based on password.
 */// w  w w  . j av a  2 s  . c  om
public SecretKey generatePkcs12(final char[] password, final int keyBitLength, final DigestAlgorithm digest,
        final byte[] salt) {
    return generate(new PKCS12ParametersGenerator(digest.getDigest()),
            PBEParametersGenerator.PKCS12PasswordToBytes(password), keyBitLength, salt);
}

From source file:edu.vt.middleware.crypt.PbeKeyGenerator.java

License:Open Source License

/**
 * Generate a key/IV pair from a text password using the PKCS#12 method
 * described at http://www.rsa.com/rsalabs/node.asp?id=2138.
 *
 * @param  password  Raw material used for key generation.
 * @param  keyBitLength  Size of generated key in bits.
 * @param  ivBitLength  Size of generated IV in bits.
 * @param  digest  Digest algorithm to use during key generation.
 * @param  salt  Key initialization data.
 *
 * @return  Secret key based on password.
 *//*from w  w  w  .ja  v  a 2  s  .  c o m*/
public KeyWithIV generatePkcs12(final char[] password, final int keyBitLength, final int ivBitLength,
        final DigestAlgorithm digest, final byte[] salt) {
    return generate(new PKCS12ParametersGenerator(digest.getDigest()),
            PBEParametersGenerator.PKCS12PasswordToBytes(password), keyBitLength, ivBitLength, salt);
}

From source file:org.cesecore.util.StringTools.java

License:Open Source License

public static String pbeEncryptStringWithSha256Aes192(final String in)
        throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException {
    CryptoProviderTools.installBCProviderIfNotAvailable();
    if (CryptoProviderTools.isUsingExportableCryptography()) {
        log.warn("Obfuscation not possible due to weak crypto policy.");
        return in;
    }/*from w  w w.j  a  v a2 s . c  om*/
    final Digest digest = new SHA256Digest();

    final PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest);
    pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(p), getSalt(), iCount);

    final ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(192, 128);
    final SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES");
    final Cipher c;
    c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));

    final byte[] enc = c.doFinal(in.getBytes("UTF-8"));

    final byte[] hex = Hex.encode(enc);
    return new String(hex);
}

From source file:org.ejbca.util.StringTools.java

License:Open Source License

public static String pbeEncryptStringWithSha256Aes192(final String in)
        throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException {
    if (CryptoProviderTools.isUsingExportableCryptography()) {
        log.warn("Obfuscation not possible due to weak crypto policy.");
        return in;
    }/*w  ww  .  ja  v a  2s.c o  m*/
    final Digest digest = new SHA256Digest();

    final PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest);
    pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(p), getSalt(), iCount);

    final ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(192, 128);
    final SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES");
    final Cipher c;
    c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));

    final byte[] enc = c.doFinal(in.getBytes("UTF-8"));

    final byte[] hex = Hex.encode(enc);
    return new String(hex);
}

From source file:org.xmind.core.internal.security.BouncyCastleSecurityProvider.java

License:Open Source License

private BufferedBlockCipher createCipher(boolean encrypt, IEncryptionData encData, String password)
        throws CoreException {
    checkEncryptionData(encData);/*  w ww.  j  a  v a 2 s.  co m*/

    // Create a parameter generator
    PKCS12ParametersGenerator paramGen = new PKCS12ParametersGenerator(new MD5Digest());

    // Get the password bytes
    byte[] pwBytes = password == null ? new byte[0]
            : PBEParametersGenerator.PKCS12PasswordToBytes(password.toCharArray());

    // Initialize the parameter generator with password bytes, 
    // salt and iteration counts
    paramGen.init(pwBytes, getSalt(encData), getIterationCount(encData));

    // Generate a parameter
    CipherParameters param = paramGen.generateDerivedParameters(128);

    // Create a block cipher
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    // Initialize the block cipher
    cipher.init(encrypt, param);
    return cipher;
}

From source file:org.xwiki.crypto.password.PasswordToByteConverter.java

License:Open Source License

/**
 * Convert password to bytes./*  w  ww  . j a v a 2  s. c  om*/
 *
 * @param password password to convert.
 * @param mode mode of conversion.
 * @return a bytes array representing the password.
 */
public static byte[] convert(char[] password, ToBytesMode mode) {
    byte[] passwd;

    switch (mode) {
    case PKCS12:
        passwd = PBEParametersGenerator.PKCS12PasswordToBytes(password);
        break;
    case PKCS5:
        passwd = PBEParametersGenerator.PKCS5PasswordToBytes(password);
        break;
    default:
        passwd = PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password);
        break;
    }

    return passwd;
}