Example usage for org.bouncycastle.crypto.params ParametersWithIV getParameters

List of usage examples for org.bouncycastle.crypto.params ParametersWithIV getParameters

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params ParametersWithIV getParameters.

Prototype

public CipherParameters getParameters() 

Source Link

Usage

From source file:com.dinochiesa.edgecallouts.util.PasswordUtil.java

License:Apache License

public static KeyAndIv deriveKeyAndIv(String plainPassword, byte[] salt, int keyBits, int ivBits,
        int iterations) {
    // Derive keys and IVs from passwords, as defined by PKCS 5 V2.0 Scheme
    // 2. This generator uses a SHA-1 HMac as the
    // calculation function. This is also known as PBKDF2, and is defined in RFC2898.
    // See https://en.wikipedia.org/wiki/PBKDF2
    PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(plainPassword.getBytes(StandardCharsets.UTF_8), salt, iterations);
    ParametersWithIV params = (ParametersWithIV) generator.generateDerivedParameters(keyBits, ivBits);
    return new KeyAndIv(((KeyParameter) params.getParameters()).getKey(), params.getIV());
}

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

License:Open Source License

/**
 * SecureCrypto Constructor./*from ww w  .  j a v a2 s. c  o  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);/* ww w  . j  a  va2 s.co m*/

    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:com.thecorpora.qbo.androidapk.AESCipher.java

License:Open Source License

private ParametersWithIV getKeyParamWithIv(String keyphrase, byte[] salt) {
    int iterationCount = 1;
    //creating generator for PBE derived keys and ivs as used by open ssl
    PBEParametersGenerator generator = new OpenSSLPBEParametersGenerator();

    //intialse the PBE generator with password, salt and iteration count
    generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(keyphrase.toCharArray()), salt, iterationCount);

    //Generate a key with initialisation vector parameter derived from the password, salt and iteration count
    ParametersWithIV paramWithIv = (ParametersWithIV) generator.generateDerivedParameters(256, 128);
    KeyParameter keyParam = (KeyParameter) paramWithIv.getParameters();

    return paramWithIv;
}

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

License:Open Source License

/**
 * Generate an encryption key/IV pair from a password using the given
 * parameter generator./*from  ww  w  .  j ava 2s.co m*/
 *
 * @param  generator  Key generator for specific PBE method.
 * @param  password  Password as byte array (depends on PBE method).
 * @param  keyBitLength  Size of generated key in bits.
 * @param  ivBitLength  Size of generated IV in bits.
 * @param  salt  Key initialization data.
 *
 * @return  Secret key derived from password using PBE key generation method.
 */
private KeyWithIV generate(final PBEParametersGenerator generator, final byte[] password,
        final int keyBitLength, final int ivBitLength, final byte[] salt) {
    generator.init(password, salt, iterations);

    final ParametersWithIV params = (ParametersWithIV) generator.generateDerivedParameters(keyBitLength,
            ivBitLength);
    final KeyParameter keyParam = (KeyParameter) params.getParameters();
    return new KeyWithIV(new SecretKeySpec(keyParam.getKey(), symmetricAlg.getAlgorithm()), params.getIV());
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypter.java

License:Apache License

protected void writeKeyfile(TarArchiveOutputStream tarArchiveOutputStream, ParametersWithIV cipherParameters)
        throws IOException, InvalidCipherTextException {
    final KeyParameter keyParameter = (KeyParameter) cipherParameters.getParameters();

    final byte[] keyBytes = keyParameter.getKey();
    final char[] keyHexChars = Hex.encodeHex(keyBytes);

    final byte[] ivBytes = cipherParameters.getIV();
    final char[] ivHexChars = Hex.encodeHex(ivBytes);

    //Create keyfile contents
    final String keyfileString = new StringBuilder(keyHexChars.length + 1 + ivHexChars.length)
            .append(keyHexChars).append(KEYFILE_LINE_SEPERATOR).append(ivHexChars).toString();

    encryptAndWrite(tarArchiveOutputStream, keyfileString, KEYFILE_ENC_NAME);
}

From source file:freenet.crypt.OCBBlockCipher_v149.java

License:Open Source License

public void init(boolean forEncryption, CipherParameters parameters) throws IllegalArgumentException {
    this.forEncryption = forEncryption;
    this.macBlock = null;

    KeyParameter keyParameter;/* w  ww  .  j  a  va  2  s.  com*/

    byte[] N;
    if (parameters instanceof AEADParameters) {
        AEADParameters aeadParameters = (AEADParameters) parameters;

        N = aeadParameters.getNonce();
        initialAssociatedText = aeadParameters.getAssociatedText();

        int macSizeBits = aeadParameters.getMacSize();
        if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0) {
            throw new IllegalArgumentException("Invalid value for MAC size: " + macSizeBits);
        }

        macSize = macSizeBits / 8;
        keyParameter = aeadParameters.getKey();
    } else if (parameters instanceof ParametersWithIV) {
        ParametersWithIV parametersWithIV = (ParametersWithIV) parameters;

        N = parametersWithIV.getIV();
        initialAssociatedText = null;
        macSize = 16;
        keyParameter = (KeyParameter) parametersWithIV.getParameters();
    } else {
        throw new IllegalArgumentException("invalid parameters passed to OCB");
    }

    this.hashBlock = new byte[16];
    this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];

    if (N == null) {
        N = new byte[0];
    }

    /*
     * TODO There's currently a thread on CFRG
     * (http://www.ietf.org/mail-archive/web/cfrg/current/msg03433.html) debating including
     * (macSize % 128) in the nonce, in which case this test becomes simpler:
     */
    //        if (N.length > 15)
    //        {
    //            throw new IllegalArgumentException("IV must be no more than 120 bits");
    //        }
    if (N.length > 16 || (N.length == 16 && (N[0] & 0x80) != 0)) {
        /*
         * NOTE: We don't just ignore bit 128 because it would hide from the caller the fact
         * that two nonces differing only in bit 128 are not different.
         */
        throw new IllegalArgumentException("IV must be no more than 127 bits");
    }

    /*
     * KEY-DEPENDENT INITIALISATION
     */

    if (keyParameter == null) {
        // TODO If 'keyParameter' is null we're re-using the last key.
    }

    // hashCipher always used in forward mode
    hashCipher.init(true, keyParameter);
    mainCipher.init(forEncryption, keyParameter);

    this.L_Asterisk = new byte[16];
    hashCipher.processBlock(L_Asterisk, 0, L_Asterisk, 0);

    this.L_Dollar = OCB_double(L_Asterisk);

    this.L = new Vector();
    this.L.addElement(OCB_double(L_Dollar));

    /*
     * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
     */

    byte[] nonce = new byte[16];
    System.arraycopy(N, 0, nonce, nonce.length - N.length, N.length);

    /*
     * TODO There's currently a thread on CFRG
     * (http://www.ietf.org/mail-archive/web/cfrg/current/msg03433.html) debating including
     * (macSize % 128) in the nonce, in which case this code becomes simpler:
     */
    //        nonce[0] = (byte)(macSize << 4);
    //        nonce[15 - N.length] |= 1;
    if (N.length == 16) {
        nonce[0] &= 0x80;
    } else {
        nonce[15 - N.length] = 1;
    }

    int bottom = nonce[15] & 0x3F;
    // System.out.println("bottom: " + bottom);

    byte[] Ktop = new byte[16];
    nonce[15] &= 0xC0;
    hashCipher.processBlock(nonce, 0, Ktop, 0);

    byte[] Stretch = new byte[24];
    System.arraycopy(Ktop, 0, Stretch, 0, 16);
    for (int i = 0; i < 8; ++i) {
        Stretch[16 + i] = (byte) (Ktop[i] ^ Ktop[i + 1]);
    }

    this.OffsetMAIN_0 = new byte[16];
    int bits = bottom % 8, bytes = bottom / 8;
    if (bits == 0) {
        System.arraycopy(Stretch, bytes, OffsetMAIN_0, 0, 16);
    } else {
        for (int i = 0; i < 16; ++i) {
            int b1 = Stretch[bytes] & 0xff;
            int b2 = Stretch[++bytes] & 0xff;
            this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >>> (8 - bits)));
        }
    }

    this.hashBlockPos = 0;
    this.mainBlockPos = 0;

    this.hashBlockCount = 0;
    this.mainBlockCount = 0;

    this.OffsetHASH = new byte[16];
    this.Sum = new byte[16];
    this.OffsetMAIN = Arrays.clone(this.OffsetMAIN_0);
    this.Checksum = new byte[16];

    if (initialAssociatedText != null) {
        processAADBytes(initialAssociatedText, 0, initialAssociatedText.length);
    }
}

From source file:org.bunkr.core.descriptor.PBKDF2Descriptor.java

License:Open Source License

@Override
public Inventory readInventoryFromBytes(byte[] source, UserSecurityProvider usp) throws BaseBunkrException {
    try {//w ww .j ava  2  s.  com
        if (this.encryptionAlgorithm == Encryption.NONE)
            throw new IllegalArgumentException("PBKDF2Descriptor requires an active encryption mode");

        PKCS5S2ParametersGenerator g = new PKCS5S2ParametersGenerator(new SHA256Digest());
        g.init(usp.getHashedPassword(), this.pbkdf2Salt, this.pbkdf2Iterations);
        ParametersWithIV kp = (ParametersWithIV) g.generateDerivedParameters(
                this.encryptionAlgorithm.keyByteLength * 8, this.encryptionAlgorithm.ivByteLength * 8);

        byte[] decryptedInv = SimpleAES.decrypt(this.encryptionAlgorithm, source,
                ((KeyParameter) kp.getParameters()).getKey(), kp.getIV());

        return InventoryJSON.decode(new String(decryptedInv));
    } catch (IllegalPasswordException | CryptoException e) {
        throw new BaseBunkrException(e);
    }
}

From source file:org.bunkr.core.descriptor.PBKDF2Descriptor.java

License:Open Source License

@Override
public byte[] writeInventoryToBytes(Inventory source, UserSecurityProvider usp) throws BaseBunkrException {
    try {//from   w  w  w  . ja v  a  2 s .  c om
        byte[] inventoryJsonBytes = InventoryJSON.encode(source).getBytes();

        if (this.encryptionAlgorithm == Encryption.NONE)
            throw new IllegalArgumentException("PBKDF2Descriptor requires an active encryption mode");

        // first refresh the salt
        RandomMaker.fill(this.pbkdf2Salt);

        PKCS5S2ParametersGenerator g = new PKCS5S2ParametersGenerator(new SHA256Digest());
        g.init(usp.getHashedPassword(), this.pbkdf2Salt, this.pbkdf2Iterations);
        ParametersWithIV kp = (ParametersWithIV) g.generateDerivedParameters(
                this.encryptionAlgorithm.keyByteLength * 8, this.encryptionAlgorithm.ivByteLength * 8);

        // encrypt the inventory
        byte[] encryptedInv = SimpleAES.encrypt(this.encryptionAlgorithm, inventoryJsonBytes,
                ((KeyParameter) kp.getParameters()).getKey(), kp.getIV());
        Arrays.fill(inventoryJsonBytes, (byte) 0);

        return encryptedInv;
    } catch (IllegalPasswordException | CryptoException e) {
        throw new BaseBunkrException(e);
    }
}

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  .  com
    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);
}