Example usage for org.bouncycastle.crypto.generators OpenSSLPBEParametersGenerator generateDerivedParameters

List of usage examples for org.bouncycastle.crypto.generators OpenSSLPBEParametersGenerator generateDerivedParameters

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.generators OpenSSLPBEParametersGenerator generateDerivedParameters.

Prototype

public CipherParameters generateDerivedParameters(int keySize) 

Source Link

Document

Generate a key parameter derived from the password, salt, and iteration count we are currently initialised with.

Usage

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

License:Open Source License

/** {@inheritDoc} */
public byte[] generate(final char[] password, final int size) {
    final OpenSSLPBEParametersGenerator generator = new OpenSSLPBEParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(password), salt);

    final KeyParameter p = (KeyParameter) generator.generateDerivedParameters(size);
    return p.getKey();
}

From source file:org.cryptacular.pbe.OpenSSLEncryptionScheme.java

License:Open Source License

/**
 * Creates a new instance using the given parameters.
 *
 * @param  cipher  Buffered block cipher algorithm.
 * @param  salt  Salt data for key generation function.
 * @param  keyBitLength  Size of derived keys in bits.
 * @param  password  Password used to derive key.
 *///from  w  ww.  j a v  a  2  s.  c  om
public OpenSSLEncryptionScheme(final BufferedBlockCipher cipher, final byte[] salt, final int keyBitLength,
        final char[] password) {
    final OpenSSLPBEParametersGenerator generator = new OpenSSLPBEParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password), salt);
    setCipher(cipher);
    setCipherParameters(generator.generateDerivedParameters(keyBitLength));
}

From source file:org.cryptacular.pbe.OpenSSLEncryptionScheme.java

License:Open Source License

/**
 * Creates a new instance from an algorithm and salt data.
 *
 * @param  algorithm  OpenSSL key encryption algorithm.
 * @param  iv  Explicit IV; first 8 bytes also used for salt in PBE key
 *             generation./* w  ww. jav  a 2  s  .  com*/
 * @param  password  Password used to derive key.
 */
public OpenSSLEncryptionScheme(final OpenSSLAlgorithm algorithm, final byte[] iv, final char[] password) {
    byte[] salt = iv;
    if (iv.length > 8) {
        salt = new byte[8];
        System.arraycopy(iv, 0, salt, 0, 8);
    }

    final OpenSSLPBEParametersGenerator generator = new OpenSSLPBEParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password), salt);
    setCipher(algorithm.getCipherSpec().newInstance());
    setCipherParameters(new ParametersWithIV(
            generator.generateDerivedParameters(algorithm.getCipherSpec().getKeyLength()), iv));
}

From source file:org.jruby.ext.openssl.impl.pem.PEMUtilities.java

License:Open Source License

private static SecretKey getKey(char[] password, String algorithm, int keyLength, byte[] salt, boolean des2) {
    OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();

    pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(password), salt);

    KeyParameter keyParam;/*from w  w  w. j a  va 2 s. c  o m*/
    keyParam = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
    byte[] key = keyParam.getKey();
    if (des2 && key.length >= 24) {
        // For DES2, we must copy first 8 bytes into the last 8 bytes.
        System.arraycopy(key, 0, key, 16, 8);
    }
    return new SecretKeySpec(key, algorithm);
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

@Override
public void writeDSAPrivateKey(Writer _out, DSAPrivateKey obj, String algo, char[] f) throws IOException {
    BufferedWriter out = makeBuffered(_out);
    ByteArrayInputStream bIn = new ByteArrayInputStream(getEncoded(obj));
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) aIn.readObject());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new DERInteger(0));
    v.add(new DERInteger(p.getP()));
    v.add(new DERInteger(p.getQ()));
    v.add(new DERInteger(p.getG()));

    BigInteger x = obj.getX();//from  w  w w  .j  a v a  2  s . c  o  m
    BigInteger y = p.getG().modPow(x, p.getP());

    v.add(new DERInteger(y));
    v.add(new DERInteger(x));

    aOut.writeObject(new DERSequence(v));
    byte[] encoding = bOut.toByteArray();

    if (algo != null && f != null) {
        byte[] salt = new byte[8];
        byte[] encData = null;
        random.nextBytes(salt);
        OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
        pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(f), salt);
        SecretKey secretKey = null;
        if (algo.equalsIgnoreCase("DESede/CBC/PKCS5Padding")) {
            // generate key
            int keyLength = 24;
            KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
            secretKey = new SecretKeySpec(param.getKey(), "DESede");
        } else {
            throw new IOException("unknown algorithm in write_DSAPrivateKey: " + algo);
        }

        // cipher  
        try {
            Cipher c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(salt));
            encData = c.doFinal(encoding);
        } catch (Exception e) {
            throw new IOException("exception using cipher: " + e.toString());
        }

        // write the data
        out.write(BEF_G + PEM_STRING_DSA + AFT);
        out.newLine();
        out.write("Proc-Type: 4,ENCRYPTED");
        out.newLine();
        out.write("DEK-Info: DES-EDE3-CBC,");
        writeHexEncoded(out, salt);
        out.newLine();
        out.newLine();
        writeEncoded(out, encData);
        out.write(BEF_E + PEM_STRING_DSA + AFT);
        out.flush();
    } else {
        out.write(BEF_G + PEM_STRING_DSA + AFT);
        out.newLine();
        writeEncoded(out, encoding);
        out.write(BEF_E + PEM_STRING_DSA + AFT);
        out.newLine();
        out.flush();
    }
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

@Override
public void writeRSAPrivateKey(Writer _out, RSAPrivateCrtKey obj, String algo, char[] f) throws IOException {
    assert (obj != null);
    BufferedWriter out = makeBuffered(_out);
    RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(obj.getModulus(), obj.getPublicExponent(),
            obj.getPrivateExponent(), obj.getPrimeP(), obj.getPrimeQ(), obj.getPrimeExponentP(),
            obj.getPrimeExponentQ(), obj.getCrtCoefficient());

    // convert to bytearray
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    aOut.writeObject(keyStruct);//from ww  w  . j  a  v  a2  s. com
    aOut.close();

    byte[] encoding = bOut.toByteArray();

    if (algo != null && f != null) {
        byte[] salt = new byte[8];
        byte[] encData = null;
        random.nextBytes(salt);
        OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
        pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(f), salt);
        SecretKey secretKey = null;

        if (algo.startsWith("DES")) {
            // generate key
            int keyLength = 24;
            if (algo.equalsIgnoreCase("DESEDE")) {
                algo = "DESede/CBC/PKCS5Padding";
            }
            KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
            secretKey = new SecretKeySpec(param.getKey(), algo.split("/")[0]);
        } else {
            throw new IOException("unknown algorithm `" + algo + "' in write_DSAPrivateKey");
        }

        // cipher  
        try {
            Cipher c = Cipher.getInstance(algo);
            c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(salt));
            encData = c.doFinal(encoding);
        } catch (Exception e) {
            throw new IOException("exception using cipher: " + e.toString());
        }

        // write the data
        out.write(BEF_G + PEM_STRING_RSA + AFT);
        out.newLine();
        out.write("Proc-Type: 4,ENCRYPTED");
        out.newLine();
        out.write("DEK-Info: DES-EDE3-CBC,");
        writeHexEncoded(out, salt);
        out.newLine();
        out.newLine();
        writeEncoded(out, encData);
        out.write(BEF_E + PEM_STRING_RSA + AFT);
        out.flush();
    } else {
        out.write(BEF_G + PEM_STRING_RSA + AFT);
        out.newLine();
        writeEncoded(out, encoding);
        out.write(BEF_E + PEM_STRING_RSA + AFT);
        out.newLine();
        out.flush();
    }
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

/**
 * create the secret key needed for this object, fetching the password
 *///w w  w  .  ja  v a2 s  .  com
private SecretKey getKey(char[] k1, String algorithm, int keyLength, byte[] salt) throws IOException {
    char[] password = k1;
    if (password == null) {
        throw new IOException("Password is null, but a password is required");
    }
    OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
    pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(password), salt);
    KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
    return new javax.crypto.spec.SecretKeySpec(param.getKey(), algorithm);
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

private static void writePemEncrypted(BufferedWriter out, String pemHeader, byte[] encoding, CipherSpec cipher,
        char[] passwd) throws IOException {
    Cipher c = cipher.getCipher();
    byte[] iv = new byte[c.getBlockSize()];
    random.nextBytes(iv);//from  www .j  a  va2 s.com
    byte[] salt = new byte[8];
    System.arraycopy(iv, 0, salt, 0, 8);
    OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
    pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(passwd), salt);
    KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(cipher.getKeyLenInBits());
    SecretKey secretKey = new SecretKeySpec(param.getKey(),
            org.jruby.ext.openssl.Cipher.Algorithm.getAlgorithmBase(c));
    byte[] encData = null;
    try {
        c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
        encData = c.doFinal(encoding);
    } catch (InvalidKeyException ike) {
        if (ike.getMessage().startsWith("Invalid key length")) {
            throw new IOException("Invalid key length. See http://wiki.jruby.org/UnlimitedStrengthCrypto");
        }
        throw new IOException("exception using cipher:" + ike.toString(), ike);
    } catch (GeneralSecurityException gse) {
        throw new IOException("exception using cipher: " + gse.toString(), gse);
    }
    out.write(BEF_G + pemHeader + AFT);
    out.newLine();
    out.write("Proc-Type: 4,ENCRYPTED");
    out.newLine();
    out.write("DEK-Info: " + cipher.getOsslName() + ",");
    writeHexEncoded(out, iv);
    out.newLine();
    out.newLine();
    writeEncoded(out, encData);
    out.write(BEF_E + pemHeader + AFT);
    out.flush();
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

private static byte[] decrypt(byte[] decoded, String dekInfo, char[] passwd)
        throws IOException, GeneralSecurityException {
    if (passwd == null) {
        throw new IOException("Password is null, but a password is required");
    }/* w  w w . j a  va 2  s  .  c  om*/
    StringTokenizer tknz = new StringTokenizer(dekInfo, ",");
    String algorithm = tknz.nextToken();
    byte[] iv = Hex.decode(tknz.nextToken());
    if (!CipherModule.isSupportedCipher(algorithm)) {
        throw new IOException("Unknown algorithm: " + algorithm);
    }
    String[] cipher = org.jruby.ext.openssl.Cipher.Algorithm.osslToJsse(algorithm);
    String realName = cipher[3];
    int[] lengths = org.jruby.ext.openssl.Cipher.Algorithm.osslKeyIvLength(algorithm);
    int keyLen = lengths[0];
    int ivLen = lengths[1];
    if (iv.length != ivLen) {
        throw new IOException("Illegal IV length");
    }
    byte[] salt = new byte[8];
    System.arraycopy(iv, 0, salt, 0, 8);
    OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
    pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(passwd), salt);
    KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLen * 8);
    SecretKey secretKey = new javax.crypto.spec.SecretKeySpec(param.getKey(), realName);
    Cipher c = Cipher.getInstance(realName);
    c.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
    return c.doFinal(decoded);
}