Example usage for org.bouncycastle.bcpg SymmetricKeyAlgorithmTags AES_256

List of usage examples for org.bouncycastle.bcpg SymmetricKeyAlgorithmTags AES_256

Introduction

In this page you can find the example usage for org.bouncycastle.bcpg SymmetricKeyAlgorithmTags AES_256.

Prototype

int AES_256

To view the source code for org.bouncycastle.bcpg SymmetricKeyAlgorithmTags AES_256.

Click Source Link

Usage

From source file:genkeys.java

License:Open Source License

private static String symmetricCipherName(int algorithm) throws PGPException {
    switch (algorithm) {
    case SymmetricKeyAlgorithmTags.NULL:
        return null;
    case SymmetricKeyAlgorithmTags.TRIPLE_DES:
        return "DESEDE";
    case SymmetricKeyAlgorithmTags.IDEA:
        return "IDEA";
    case SymmetricKeyAlgorithmTags.CAST5:
        return "CAST5";
    case SymmetricKeyAlgorithmTags.BLOWFISH:
        return "Blowfish";
    case SymmetricKeyAlgorithmTags.SAFER:
        return "SAFER";
    case SymmetricKeyAlgorithmTags.DES:
        return "DES";
    case SymmetricKeyAlgorithmTags.AES_128:
        return "AES";
    case SymmetricKeyAlgorithmTags.AES_192:
        return "AES";
    case SymmetricKeyAlgorithmTags.AES_256:
        return "AES";
    case SymmetricKeyAlgorithmTags.TWOFISH:
        return "Twofish";
    default://from ww  w  . j  a v a2  s  .  c om
        throw new PGPException("unknown symmetric algorithm: " + algorithm);
    }
}

From source file:de.unioninvestment.crud2go.spi.security.pgp.PGPCryptor.java

License:Apache License

@Override
public String encrypt(String toEncrypt) {
    try {//from   w ww.  j a v  a  2 s  .c  o m
        byte[] message = toEncrypt.getBytes(TEXT_ENCODING);
        byte[] encMessage = PGPCryptoUtil.encrypt(message, new PGPPublicKey[] { publicKey },
                SymmetricKeyAlgorithmTags.AES_256);
        return new String(encMessage, "ascii");

    } catch (Exception e) {
        throw new EncryptionException("error during PGP encrypting", e);
    }
}

From source file:divconq.pgp.PGPUtil.java

License:Open Source License

public static String getSymmetricCipherName(int algorithm) {
    switch (algorithm) {
    case SymmetricKeyAlgorithmTags.NULL:
        return null;
    case SymmetricKeyAlgorithmTags.TRIPLE_DES:
        return "DESEDE";
    case SymmetricKeyAlgorithmTags.IDEA:
        return "IDEA";
    case SymmetricKeyAlgorithmTags.CAST5:
        return "CAST5";
    case SymmetricKeyAlgorithmTags.BLOWFISH:
        return "Blowfish";
    case SymmetricKeyAlgorithmTags.SAFER:
        return "SAFER";
    case SymmetricKeyAlgorithmTags.DES:
        return "DES";
    case SymmetricKeyAlgorithmTags.AES_128:
        return "AES";
    case SymmetricKeyAlgorithmTags.AES_192:
        return "AES";
    case SymmetricKeyAlgorithmTags.AES_256:
        return "AES";
    case SymmetricKeyAlgorithmTags.CAMELLIA_128:
        return "Camellia";
    case SymmetricKeyAlgorithmTags.CAMELLIA_192:
        return "Camellia";
    case SymmetricKeyAlgorithmTags.CAMELLIA_256:
        return "Camellia";
    case SymmetricKeyAlgorithmTags.TWOFISH:
        return "Twofish";
    default:/* w  w w. j  a va 2  s  . c om*/
        throw new IllegalArgumentException("unknown symmetric algorithm: " + algorithm);
    }
}

From source file:keygenerator.KeyGenerator.java

public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass, int s2kcount)
        throws Exception {
    // This object generates individual key-pairs.
    RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();

    // Boilerplate RSA parameters, no need to change anything
    // except for the RSA key-size (2048). You can use whatever
    // key-size makes sense for you -- 4096, etc.
    kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12));

    // First create the master (signing) key with the generator.
    PGPKeyPair rsakp_sign = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpg.generateKeyPair(), new Date());
    // Then an encryption subkey.
    PGPKeyPair rsakp_enc = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, kpg.generateKeyPair(), new Date());

    // Add a self-signature on the id
    PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();

    // Add signed metadata on the signature.
    // 1) Declare its purpose
    signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER);
    // 2) Set preferences for secondary crypto algorithms to use
    //    when sending messages to this key.
    signhashgen.setPreferredSymmetricAlgorithms(false, new int[] { SymmetricKeyAlgorithmTags.AES_256,
            SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 });
    signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1,
            HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224, });
    // 3) Request senders add additional checksums to the
    //    message (useful when verifying unsigned messages.)
    signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION);

    // Create a signature on the encryption subkey.
    PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator();
    // Add metadata to declare its purpose
    enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE);

    // Objects used to encrypt the secret key.
    PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1);
    PGPDigestCalculator sha256Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256);

    // bcpg 1.48 exposes this API that includes s2kcount. Earlier
    // versions use a default of 0x60.
    PBESecretKeyEncryptor pske = (new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha256Calc,
            s2kcount)).build(pass);/*  www  .j  a  va2s . c o m*/

    // Finally, create the keyring itself. The constructor
    // takes parameters that allow it to generate the self
    // signature.

    BcPGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(
            rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1);

    PGPKeyRingGenerator keyRingGen;
    keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc,
            signhashgen.generate(), null, signerBuilder, pske);

    // Add our encryption subkey, together with its signature.
    keyRingGen.addSubKey(rsakp_enc, enchashgen.generate(), null);
    return keyRingGen;
}

From source file:net.tjado.passwdsafe.UsbGpgBackupActivity.java

License:Open Source License

public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey)
        throws IOException, PGPException {
    Security.addProvider(new BouncyCastleProvider());

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);

    PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
    comData.close();//from ww  w  .  j  a  v a  2s .com

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
            new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256).setSecureRandom(new SecureRandom())
                    .setWithIntegrityPacket(true));
    cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));

    byte[] bytes = bOut.toByteArray();

    OutputStream cOut;
    cOut = cPk.open(out, bytes.length);
    cOut.write(bytes);
    cOut.close();

    out.close();
}

From source file:org.sufficientlysecure.keychain.pgp.UncachedKeyringCanonicalizeTest.java

License:Open Source License

@Test
public void testDuplicateSubkey() throws Exception {

    { // duplicate subkey

        // get subkey packets
        Iterator<RawPacket> it = KeyringTestingHelper.parseKeyring(ring.getEncoded());
        RawPacket subKey = KeyringTestingHelper.getNth(it, 7);
        RawPacket subSig = it.next();/*  w ww. j  a  v a 2 s.c o m*/

        // inject at a second position
        UncachedKeyRing modified = ring;
        modified = KeyringTestingHelper.injectPacket(modified, subKey.buf, 9);
        modified = KeyringTestingHelper.injectPacket(modified, subSig.buf, 10);

        // canonicalize, and check if we lose the bad signature
        OperationLog log = new OperationLog();
        CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
        Assert.assertNull("canonicalization with duplicate subkey should fail", canonicalized);
        Assert.assertTrue("log should contain dup_key event", log.containsType(LogType.MSG_KC_ERROR_DUP_KEY));
    }

    { // duplicate subkey, which is the same as the master key

        // We actually encountered one of these in the wild:
        // https://www.sparkasse-holstein.de/firmenkunden/electronic_banking/secure-e-mail/pdf/Spk_Holstein_PGP_Domain-Zertifikat.asc

        CanonicalizedSecretKeyRing canonicalized = (CanonicalizedSecretKeyRing) ring.canonicalize(log, 0);

        CanonicalizedSecretKey masterSecretKey = canonicalized.getSecretKey();
        masterSecretKey.unlock(new Passphrase());
        PGPPublicKey masterPublicKey = masterSecretKey.getPublicKey();
        CryptoInputParcel cryptoInput = new CryptoInputParcel(new Date());
        PGPSignature cert = PgpKeyOperation.generateSubkeyBindingSignature(
                PgpKeyOperation.getSignatureGenerator(masterSecretKey.getSecretKey(), cryptoInput),
                cryptoInput.getSignatureTime(), masterPublicKey, masterSecretKey.getPrivateKey(),
                PgpKeyOperation.getSignatureGenerator(masterSecretKey.getSecretKey(), null),
                masterSecretKey.getPrivateKey(), masterPublicKey, masterSecretKey.getKeyUsage(), 0);
        PGPPublicKey subPubKey = PGPPublicKey.addSubkeyBindingCertification(masterPublicKey, cert);

        PGPSecretKey sKey;
        {
            // Build key encrypter and decrypter based on passphrase
            PGPDigestCalculator encryptorHashCalc = new JcaPGPDigestCalculatorProviderBuilder().build()
                    .get(HashAlgorithmTags.SHA256);
            PBESecretKeyEncryptor keyEncryptor = new JcePBESecretKeyEncryptorBuilder(
                    SymmetricKeyAlgorithmTags.AES_256, encryptorHashCalc, 10)
                            .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());

            // NOTE: only SHA1 is supported for key checksum calculations.
            PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build()
                    .get(HashAlgorithmTags.SHA1);
            sKey = new PGPSecretKey(masterSecretKey.getPrivateKey(), subPubKey, sha1Calc, false, keyEncryptor);
        }

        UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sKey.getEncoded(), 7);

        // canonicalize, and check if we lose the bad signature
        OperationLog log = new OperationLog();
        CanonicalizedKeyRing result = modified.canonicalize(log, 0);
        Assert.assertNull("canonicalization with duplicate subkey (from master) should fail", result);
        Assert.assertTrue("log should contain dup_key event", log.containsType(LogType.MSG_KC_ERROR_DUP_KEY));
    }

}

From source file:org.sufficientlysecure.keychain.support.KeyringBuilder.java

License:Open Source License

private static SignaturePacket createSignaturePacket(BigInteger signature) {
    MPInteger[] signatureArray = new MPInteger[] { new MPInteger(signature) };

    int signatureType = PGPSignature.POSITIVE_CERTIFICATION;
    int keyAlgorithm = SignaturePacket.RSA_GENERAL;
    int hashAlgorithm = HashAlgorithmTags.SHA1;

    SignatureSubpacket[] hashedData = new SignatureSubpacket[] {
            new SignatureCreationTime(false, SIGNATURE_DATE),
            new KeyFlags(false, KeyFlags.CERTIFY_OTHER + KeyFlags.SIGN_DATA),
            new KeyExpirationTime(false, TimeUnit.DAYS.toSeconds(2)),
            new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_SYM_ALGS, false,
                    new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192,
                            SymmetricKeyAlgorithmTags.AES_128, SymmetricKeyAlgorithmTags.CAST5,
                            SymmetricKeyAlgorithmTags.TRIPLE_DES }),
            new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_HASH_ALGS, false,
                    new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384,
                            HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224 }),
            new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_COMP_ALGS, false,
                    new int[] { CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2,
                            CompressionAlgorithmTags.ZIP }),
            new Features(false, Features.FEATURE_MODIFICATION_DETECTION),
            createPreferencesSignatureSubpacket() };
    SignatureSubpacket[] unhashedData = new SignatureSubpacket[] {
            new IssuerKeyID(false, false, KEY_ID.toByteArray()) };
    byte[] fingerPrint = new BigInteger("522c", 16).toByteArray();

    return new SignaturePacket(signatureType, KEY_ID.longValue(), keyAlgorithm, hashAlgorithm, hashedData,
            unhashedData, fingerPrint, signatureArray);
}

From source file:org.tramaci.onionmail.PGPKeyGen.java

License:Open Source License

public static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass, int s2kcount, int nBits,
        int certainty, Date when) throws Exception {

    RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();
    RSAKeyGenerationParameters kgp = new RSAKeyGenerationParameters(DEFAULT_PUBEXP, new SecureRandom(), nBits,
            certainty);/*from  ww w  .  j a  va 2s  . c om*/
    kpg.init(kgp);
    PGPKeyPair rsakpSign = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpg.generateKeyPair(), when);
    PGPKeyPair rsakpEnc = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, kpg.generateKeyPair(), when);
    PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();

    signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER);

    signhashgen.setPreferredSymmetricAlgorithms(false,
            new int[] { SymmetricKeyAlgorithmTags.CAST5, SymmetricKeyAlgorithmTags.AES_256,
                    SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.TWOFISH,
                    SymmetricKeyAlgorithmTags.AES_128 });

    signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1,
            HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224 });

    signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION);
    PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator();
    enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE);

    PGPDigestCalculator sha256Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256);
    PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1);

    PBESecretKeyEncryptor pske = (new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha256Calc,
            s2kcount)).build(pass);

    PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsakpSign, id,
            sha1Calc, signhashgen.generate(), null,
            new BcPGPContentSignerBuilder(rsakpSign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1),
            pske);

    keyRingGen.addSubKey(rsakpEnc, enchashgen.generate(), null);
    return keyRingGen;
}

From source file:ubicrypt.core.crypto.PGPEC.java

License:Open Source License

private static PGPKeyRingGenerator keyRingGenerator(final PGPKeyPair masterKey,
        final PBESecretKeyEncryptor encryptor) {
    // Add a self-signature on the id
    final PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();

    // Add signed metadata on the signature.
    // 1) Declare its purpose
    signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER);
    // 2) Set preferences for secondary crypto algorithms to use
    //    when sending messages to this key.
    signhashgen.setPreferredSymmetricAlgorithms(false, new int[] { SymmetricKeyAlgorithmTags.AES_256,
            SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 });
    signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA256,
            //                        HashAlgorithmTags.SHA1,
            HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224, });
    // 3) Request senders add additional checksums to the
    //    message (useful when verifying unsigned messages.)
    signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION);

    try {//  w  w  w . ja  v a2  s .c  om
        return new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, masterKey, Utils.machineName(),
                new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), signhashgen.generate(), null,
                new BcPGPContentSignerBuilder(PGPPublicKey.ECDSA, HashAlgorithmTags.SHA256), encryptor);
    } catch (final PGPException e) {
        Throwables.propagate(e);
    }
    return null;
}

From source file:ubicrypt.core.crypto.PGPEC.java

License:Open Source License

public static InputStream encrypt(final List<PGPPublicKey> pks, final InputStream clearBytes) {
    final PipedInputStream pis = new PipedInputStream();
    final AtomicReference<PipedOutputStream> pos = new AtomicReference<>();
    final AtomicReference<OutputStream> pgpOut = new AtomicReference<>();
    final AtomicReference<OutputStream> lout = new AtomicReference<>();
    try {/*from   w  w w.  ja  v  a2  s .com*/
        pos.set(new PipedOutputStream(pis));
        final PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();

        final PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256).setWithIntegrityPacket(true)
                        .setProvider("BC").setSecureRandom(new SecureRandom()));

        pks.stream().forEach(
                pk -> cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(pk).setProvider("BC")));
        pgpOut.set(cPk.open(pos.get(), new byte[1 << 16]));
        lout.set(lData.open(pgpOut.get(), PGPLiteralDataGenerator.BINARY, PGPLiteralData.CONSOLE, new Date(),
                new byte[1 << 64]));

        Observable.create(new OnSubscribeInputStream(clearBytes, 1 << 64)).subscribeOn(Schedulers.io())
                .doOnCompleted(() -> Utils.close(lout.get(), pgpOut.get(), pos.get())).doOnError(err -> {
                    log.error("error on encrypt", err);
                    Utils.close(clearBytes, lout.get(), pgpOut.get(), pos.get());
                }).subscribe(ConsumerExp.silent(lout.get()::write));
    } catch (final Exception e) {
        Utils.close(clearBytes, lout.get(), pgpOut.get(), pos.get());
        Throwables.propagate(e);
    }
    return pis;
}