Search in sources :

Example 11 with BufferedBlockCipher

use of org.bouncycastle.crypto.BufferedBlockCipher in project jruby-openssl by jruby.

the class PEMInputOutput method derivePrivateKeyPBES2.

private static PrivateKey derivePrivateKeyPBES2(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId, char[] password) throws GeneralSecurityException, InvalidCipherTextException {
    PBES2Parameters pbeParams = PBES2Parameters.getInstance((ASN1Sequence) algId.getParameters());
    CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams);
    EncryptionScheme scheme = pbeParams.getEncryptionScheme();
    BufferedBlockCipher cipher;
    if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) {
        RC2CBCParameter rc2Params = RC2CBCParameter.getInstance(scheme);
        byte[] iv = rc2Params.getIV();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine()));
        cipher.init(false, param);
    } else {
        byte[] iv = ASN1OctetString.getInstance(scheme.getParameters()).getOctets();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
        cipher.init(false, param);
    }
    byte[] data = eIn.getEncryptedData();
    byte[] out = new byte[cipher.getOutputSize(data.length)];
    int len = cipher.processBytes(data, 0, data.length, out, 0);
    len += cipher.doFinal(out, len);
    byte[] pkcs8 = new byte[len];
    System.arraycopy(out, 0, pkcs8, 0, len);
    // It seems to work for both RSA and DSA.
    KeyFactory fact = SecurityHelper.getKeyFactory("RSA");
    return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
}
Also used : PBES2Parameters(org.bouncycastle.asn1.pkcs.PBES2Parameters) EncryptionScheme(org.bouncycastle.asn1.pkcs.EncryptionScheme) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) RC2Engine(org.bouncycastle.crypto.engines.RC2Engine) RC2CBCParameter(org.bouncycastle.asn1.pkcs.RC2CBCParameter) CipherParameters(org.bouncycastle.crypto.CipherParameters) ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) DESedeEngine(org.bouncycastle.crypto.engines.DESedeEngine) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 12 with BufferedBlockCipher

use of org.bouncycastle.crypto.BufferedBlockCipher in project sentinel-android by Samourai-Wallet.

the class AESUtil method decrypt.

// AES 256 PBKDF2 CBC iso10126 decryption
// 16 byte IV must be prepended to ciphertext - Compatible with crypto-js
public static String decrypt(String ciphertext, CharSequenceX password, int iterations) {
    final int AESBlockSize = 4;
    byte[] cipherdata = Base64.decodeBase64(ciphertext.getBytes());
    // Seperate the IV and cipher data
    byte[] iv = copyOfRange(cipherdata, 0, AESBlockSize * 4);
    byte[] input = copyOfRange(cipherdata, AESBlockSize * 4, cipherdata.length);
    PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toString().toCharArray()), iv, iterations);
    KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256);
    CipherParameters params = new ParametersWithIV(keyParam, iv);
    // setup AES cipher in CBC mode with PKCS7 padding
    BlockCipherPadding padding = new ISO10126d2Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(false, params);
    // create a temporary buffer to decode into (includes padding)
    byte[] buf = new byte[cipher.getOutputSize(input.length)];
    int len = cipher.processBytes(input, 0, input.length, buf, 0);
    try {
        len += cipher.doFinal(buf, len);
    } catch (InvalidCipherTextException icte) {
        icte.printStackTrace();
        return null;
    }
    // remove padding
    byte[] out = new byte[len];
    System.arraycopy(buf, 0, out, 0, len);
    // return string representation of decoded bytes
    String ret = null;
    try {
        ret = new String(out, "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
        return null;
    }
    return ret;
}
Also used : PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) AESEngine(org.bouncycastle.crypto.engines.AESEngine) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) PKCS5S2ParametersGenerator(org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ISO10126d2Padding(org.bouncycastle.crypto.paddings.ISO10126d2Padding) CipherParameters(org.bouncycastle.crypto.CipherParameters) ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) BlockCipherPadding(org.bouncycastle.crypto.paddings.BlockCipherPadding) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) PBEParametersGenerator(org.bouncycastle.crypto.PBEParametersGenerator)

Example 13 with BufferedBlockCipher

use of org.bouncycastle.crypto.BufferedBlockCipher in project sentinel-android by Samourai-Wallet.

the class AESUtil method encrypt.

public static String encrypt(String cleartext, CharSequenceX password, int iterations) {
    final int AESBlockSize = 4;
    if (password == null) {
        return null;
    }
    // Use secure random to generate a 16 byte iv
    SecureRandom random = new SecureRandom();
    byte[] iv = new byte[AESBlockSize * 4];
    random.nextBytes(iv);
    byte[] clearbytes = null;
    try {
        clearbytes = cleartext.getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
        return null;
    }
    PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toString().toCharArray()), iv, iterations);
    KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256);
    CipherParameters params = new ParametersWithIV(keyParam, iv);
    // setup AES cipher in CBC mode with PKCS7 padding
    BlockCipherPadding padding = new ISO10126d2Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(true, params);
    byte[] outBuf = cipherData(cipher, clearbytes);
    // Append to IV to the output
    int len1 = iv.length;
    int len2 = outBuf.length;
    byte[] ivAppended = new byte[len1 + len2];
    System.arraycopy(iv, 0, ivAppended, 0, len1);
    System.arraycopy(outBuf, 0, ivAppended, len1, len2);
    byte[] raw = Base64.encodeBase64(ivAppended);
    String ret = new String(raw);
    return ret;
}
Also used : PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) AESEngine(org.bouncycastle.crypto.engines.AESEngine) PKCS5S2ParametersGenerator(org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) SecureRandom(java.security.SecureRandom) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ISO10126d2Padding(org.bouncycastle.crypto.paddings.ISO10126d2Padding) CipherParameters(org.bouncycastle.crypto.CipherParameters) ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) BlockCipherPadding(org.bouncycastle.crypto.paddings.BlockCipherPadding) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) PBEParametersGenerator(org.bouncycastle.crypto.PBEParametersGenerator)

Example 14 with BufferedBlockCipher

use of org.bouncycastle.crypto.BufferedBlockCipher in project XobotOS by xamarin.

the class JCEBlockCipher method engineSetMode.

protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
    modeName = Strings.toUpperCase(mode);
    if (modeName.equals("ECB")) {
        ivLength = 0;
        cipher = new BufferedGenericBlockCipher(baseEngine);
    } else if (modeName.equals("CBC")) {
        ivLength = baseEngine.getBlockSize();
        cipher = new BufferedGenericBlockCipher(new CBCBlockCipher(baseEngine));
    } else if (modeName.startsWith("OFB")) {
        ivLength = baseEngine.getBlockSize();
        if (modeName.length() != 3) {
            int wordSize = Integer.parseInt(modeName.substring(3));
            cipher = new BufferedGenericBlockCipher(new OFBBlockCipher(baseEngine, wordSize));
        } else {
            cipher = new BufferedGenericBlockCipher(new OFBBlockCipher(baseEngine, 8 * baseEngine.getBlockSize()));
        }
    } else if (modeName.startsWith("CFB")) {
        ivLength = baseEngine.getBlockSize();
        if (modeName.length() != 3) {
            int wordSize = Integer.parseInt(modeName.substring(3));
            cipher = new BufferedGenericBlockCipher(new CFBBlockCipher(baseEngine, wordSize));
        } else {
            cipher = new BufferedGenericBlockCipher(new CFBBlockCipher(baseEngine, 8 * baseEngine.getBlockSize()));
        }
    } else // END android-removed
    if (modeName.startsWith("SIC")) {
        ivLength = baseEngine.getBlockSize();
        if (ivLength < 16) {
            throw new IllegalArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)");
        }
        cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher(new SICBlockCipher(baseEngine)));
    } else if (modeName.startsWith("CTR")) {
        ivLength = baseEngine.getBlockSize();
        cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher(new SICBlockCipher(baseEngine)));
    } else if (modeName.startsWith("GOFB")) {
        ivLength = baseEngine.getBlockSize();
        cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher(new GOFBBlockCipher(baseEngine)));
    } else if (modeName.startsWith("CTS")) {
        ivLength = baseEngine.getBlockSize();
        cipher = new BufferedGenericBlockCipher(new CTSBlockCipher(new CBCBlockCipher(baseEngine)));
    } else if (modeName.startsWith("CCM")) {
        ivLength = baseEngine.getBlockSize();
        cipher = new AEADGenericBlockCipher(new CCMBlockCipher(baseEngine));
    } else // END android-removed
    if (modeName.startsWith("GCM")) {
        ivLength = baseEngine.getBlockSize();
        cipher = new AEADGenericBlockCipher(new GCMBlockCipher(baseEngine));
    } else {
        throw new NoSuchAlgorithmException("can't support mode " + mode);
    }
}
Also used : GOFBBlockCipher(org.bouncycastle.crypto.modes.GOFBBlockCipher) OFBBlockCipher(org.bouncycastle.crypto.modes.OFBBlockCipher) CCMBlockCipher(org.bouncycastle.crypto.modes.CCMBlockCipher) SICBlockCipher(org.bouncycastle.crypto.modes.SICBlockCipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CFBBlockCipher(org.bouncycastle.crypto.modes.CFBBlockCipher) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) CTSBlockCipher(org.bouncycastle.crypto.modes.CTSBlockCipher) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) GOFBBlockCipher(org.bouncycastle.crypto.modes.GOFBBlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher)

Example 15 with BufferedBlockCipher

use of org.bouncycastle.crypto.BufferedBlockCipher in project inbot-utils by Inbot.

the class AESUtils method encryptBouncyCastle.

private static String encryptBouncyCastle(SecretKey secret, String plainText) {
    try {
        // prepending with md5 hash allows us to do an integrity check on decrypt to prevent returning garbage if the decrypt key is incorrect
        String md5 = HashUtils.md5(plainText);
        plainText = md5 + plainText;
        // the iv acts as a per use salt, this ensures things encrypted with the same key always have a unique salt
        // 128 bit iv because NIST AES is standardized with 128 bit blocks and iv needs to match block size, even when using 256 bit key
        byte[] iv = new byte[16];
        SECURE_RANDOM.nextBytes(iv);
        // setup cipher parameters with key and IV
        byte[] key = secret.getEncoded();
        // setup AES cipher in CBC mode with PKCS7 padding
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
        cipher.reset();
        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] plainTextBuf = plainText.getBytes(StandardCharsets.UTF_8);
        byte[] buf = new byte[cipher.getOutputSize(plainTextBuf.length)];
        int len = cipher.processBytes(plainTextBuf, 0, plainTextBuf.length, buf, 0);
        len += cipher.doFinal(buf, len);
        // copy the encrypted part of the buffer to out
        byte[] out = new byte[len];
        System.arraycopy(buf, 0, out, 0, len);
        // iv$encrypted
        return byteArrayToHexString(iv) + "$" + new String(Base64.encodeBase64URLSafe(out), StandardCharsets.UTF_8);
    } catch (DataLengthException | InvalidCipherTextException e) {
        throw new IllegalStateException("cannot encrypt", e);
    }
}
Also used : PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) AESEngine(org.bouncycastle.crypto.engines.AESEngine) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) PKCS7Padding(org.bouncycastle.crypto.paddings.PKCS7Padding) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) DataLengthException(org.bouncycastle.crypto.DataLengthException) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher)

Aggregations

BufferedBlockCipher (org.bouncycastle.crypto.BufferedBlockCipher)24 PaddedBufferedBlockCipher (org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher)19 CBCBlockCipher (org.bouncycastle.crypto.modes.CBCBlockCipher)15 AESEngine (org.bouncycastle.crypto.engines.AESEngine)14 ParametersWithIV (org.bouncycastle.crypto.params.ParametersWithIV)14 KeyParameter (org.bouncycastle.crypto.params.KeyParameter)10 CipherParameters (org.bouncycastle.crypto.CipherParameters)7 SICBlockCipher (org.bouncycastle.crypto.modes.SICBlockCipher)6 InvalidCipherTextException (org.bouncycastle.crypto.InvalidCipherTextException)5 IOException (java.io.IOException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 SecureRandom (java.security.SecureRandom)4 DataLengthException (org.bouncycastle.crypto.DataLengthException)4 PBEParametersGenerator (org.bouncycastle.crypto.PBEParametersGenerator)4 ECDHBasicAgreement (org.bouncycastle.crypto.agreement.ECDHBasicAgreement)4 SHA256Digest (org.bouncycastle.crypto.digests.SHA256Digest)4 PKCS5S2ParametersGenerator (org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator)4 HMac (org.bouncycastle.crypto.macs.HMac)4 OFBBlockCipher (org.bouncycastle.crypto.modes.OFBBlockCipher)4 AESFastEngine (org.bouncycastle.crypto.engines.AESFastEngine)3