Example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider.

Prototype

public BouncyCastleProvider() 

Source Link

Document

Construct a new provider.

Usage

From source file:de.rub.nds.tlsattacker.tlsserver.TLSServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    if (args.length == 5 && args[4].equalsIgnoreCase("BC")) {
        Security.removeProvider("SunPKCS11-NSS");
        Security.removeProvider("SunEC");
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
        System.out.println("Using BC provider");
    }// w  w w  .j a  va2s  .c o  m
    for (Provider p : Security.getProviders()) {
        System.out.println(p);
    }
    System.setProperty("java.security.debug", "ssl");
    String path;
    String password;
    String protocol;
    int port;

    if (args.length == 4 || args.length == 5) {
        path = args[0];
        password = args[1];
        protocol = args[2];
        port = Integer.parseInt(args[3]);
    } else if (args.length == 0) {
        path = PATH_TO_JKS;
        password = JKS_PASSWORD;
        protocol = PROTOCOL;
        port = PORT;
    } else {
        System.out.println("Usage (run with): java -jar [name].jar [jks-path] "
                + "[password] [protocol] [port] \n (set [protocol] to TLS)");
        return;
    }

    KeyStore keyStore = readKeyStore(path, password);
    TLSServer server = new TLSServer(keyStore, password, protocol, port);
    Thread t = new Thread(server);
    t.start();
}

From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java

License:Open Source License

public String getEncryptedMessage(byte[] data) {
    Security.addProvider(new BouncyCastleProvider());

    try {/*from   w  w w . j  ava2s .com*/

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStream out = new ArmoredOutputStream(baos);
        byte[] compressedData = compressFile(data, CompressionAlgorithmTags.ZIP);
        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(this.publicKey).setProvider("BC"));
        OutputStream cOut = encGen.open(out, compressedData.length);
        cOut.write(compressedData);
        cOut.close();
        out.close();
        baos.flush();
        return new String(baos.toByteArray());
    } catch (PGPException | IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.sign.SignMain.java

License:Open Source License

public void sign() throws DocumentException, IOException, GeneralSecurityException {

    PdfReader reader = new PdfReader(this.orgFile);
    OutputStream os = new FileOutputStream(this.orgFile.replace(".pdf", "SIGN.pdf"));
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');

    // Create appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    Rectangle cropBox = reader.getCropBox(1);
    float width = 50;
    float height = 50;
    Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20,
            cropBox.getRight() - 20, cropBox.getTop() - 20);
    appearance.setVisibleSignature(rectangle, 1, "sig");
    appearance.setLocation(getHostname());
    appearance.setReason("Evidence of document integrity");
    appearance.setCertificationLevel(1); // 1 = CERTIFIED_NO_CHANGES_ALLOWED
    appearance.setAcro6Layers(false);/*from   w ww  .  j  a  v a  2s .  com*/
    appearance.setLayer2Text("");

    //Sign
    Security.addProvider(new BouncyCastleProvider());
    TSAClient tsc = new TSAClientBouncyCastle(this.tsa_URL);
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(getPrivateKey(), "SHA-1", "BC");
    MakeSignature.signDetached(appearance, digest, signature, getCertificateChain(), null, null, tsc, 0,
            CryptoStandard.CMS);
}

From source file:de.softwareforge.pgpsigner.PGPSigner.java

License:Apache License

public static void main(final String[] args) {
    Security.addProvider(new BouncyCastleProvider());

    /*/*  ww w .ja  v a  2 s  .  co m*/
     * Debug Code. Add a Security Manager and a policy. 
     * Suggested by Simon Tuffs, unfortunately does not really help
     * the one-jar problem.
            
    if (System.getSecurityManager() == null) {
    String policy = System.getProperty("java.security.policy");
            
    if (policy == null) {
        System.setProperty("java.security.policy", "onejar:/pgpsigner.policy");
    }
    System.setSecurityManager(new SecurityManager());
    }
    */

    /*
     * DEBUG: Display all registered Security providers
     *
    Provider[] providers = Security.getProviders();
    for (int i=0; i < providers.length; i++) {
    System.out.println(providers[i].toString());
    }
    */

    PGPSigner pgpSigner = new PGPSigner(args);

    try {
        pgpSigner.run();
    } catch (RuntimeException re) {
        re.printStackTrace();
        throw re;
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.exit(0);
}

From source file:de.thorstenberger.examServer.pdf.signature.SignPdf.java

License:Open Source License

/**
 * Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this
 * pdf had the current content at the current point in time.
 *
 * @param originalPdf/*w  w  w  . j  a  v  a2 s  .  c om*/
 * @param targetPdf
 * @param pk
 * @param certChain
 * @param revoked
 * @param tsaAddress
 *          address of a rfc 3161 compatible timestamp server
 * @param reason
 *          reason for the signature
 * @param location
 *          location of signing
 * @param contact
 *          emailaddress of the person who is signing
 * @throws IOException
 * @throws DocumentException
 * @throws SignatureException
 */
public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf,
        final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress,
        final String reason, final String location, final String contact)
        throws IOException, DocumentException, SignatureException {
    // only an estimate, depends on the certificates returned by the TSA
    final int timestampSize = 4400;
    Security.addProvider(new BouncyCastleProvider());

    final PdfReader reader = new PdfReader(originalPdf);
    final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0');
    final PdfSignatureAppearance sap = stamper.getSignatureAppearance();

    // comment next lines to have an invisible signature
    sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null);
    sap.setLayer2Text("");

    final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC");
    final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>();

    // some informational fields
    sig.setReason(reason);
    sig.setLocation(location);
    sig.setContact(contact);
    sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN"));
    sig.setDate(new PdfDate(Calendar.getInstance()));

    // signing stuff
    final byte[] digest = new byte[256];
    final byte[] rsaData = new byte[20];
    sig.setExternalDigest(digest, rsaData, "RSA");
    sig.setSignInfo(pk, certChain, revoked);
    final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS);
    // *2 to get hex size, +2 for delimiters
    PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2);
    exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength()));
    sig.put(PdfName.CONTENTS, contentsLit);

    // certification; will display dialog or blue bar in Acrobat Reader

    sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

    // process all the information set above
    sap.setCryptoDictionary(sig);
    sap.preClose(exclusionSizes);

    // calculate digest (hash)
    try {
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buf = new byte[8192];
        int n;
        final InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) != -1) {
            messageDigest.update(buf, 0, n);
        }
        final byte[] hash = messageDigest.digest();

        // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA)
        final Signature sign = Signature.getInstance("SHA1withRSA");
        sign.initSign(pk);
        sign.update(hash);
        final byte[] signature = sign.sign();

        // prepare the location of the signature in the target PDF
        contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS);
        final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2];
        final PdfPKCS7 pkcs7 = sig.getSigner();
        pkcs7.setExternalDigest(signature, hash, "RSA");
        final PdfDictionary dic = new PdfDictionary();

        byte[] ssig = pkcs7.getEncodedPKCS7();
        try {
            // try to retrieve cryptographic timestamp from configured tsa server
            ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null);
        } catch (final RuntimeException e) {
            log.error("Could not retrieve timestamp from server.", e);
        }
        System.arraycopy(ssig, 0, outc, 0, ssig.length);

        // add the timestamped signature
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

        // finish up
        sap.close(dic);
    } catch (final InvalidKeyException e) {
        throw new RuntimeException("Internal implementation error! No such signature type.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException("Internal implementation error! No such algorithm type.", e);
    }
}

From source file:de.tsenger.animamea.crypto.AmCryptoProvider.java

License:Open Source License

public AmCryptoProvider() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:de.tsenger.animamea.ta.TerminalAuthentication.java

License:Open Source License

public TerminalAuthentication(DomainParameter caDomainParameter) {
    this.caDP = caDomainParameter;
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();
    randomGenerator.setSeed(rnd.nextLong());
}

From source file:debug.OfflineEmailProcessor.java

License:Open Source License

/** Creates a new instance of OfflineEmailProcessor */
public OfflineEmailProcessor(String configFile, String file) throws Exception {

    // load config
    ConfigurationData configData = new ConfigurationData(configFile);
    Security.addProvider(new BouncyCastleProvider());

    String symAlg = configData.getSetting("openpgp.symmetricalgorithm.used", "IDEA");
    int symmetricAlgorithm = 0;

    // load defaults
    if ("IDEA".compareToIgnoreCase(symAlg) == 0) {
        symmetricAlgorithm = SymmetricAlgorithmSettings.IDEA;
    } else if ("CAST5".compareToIgnoreCase(symAlg) == 0) {
        symmetricAlgorithm = SymmetricAlgorithmSettings.CAST5;
    } else if ("3DES".compareToIgnoreCase(symAlg) == 0) {
        symmetricAlgorithm = SymmetricAlgorithmSettings.TRIPLEDES;
    } else {/* w  ww . j  a  v  a2s  .  com*/
        System.err.println("Symmetric algorithm '" + symAlg + "' is not supported.");
    }

    // Load key manager lists
    KeyHandler publicKeyManagers[] = null;
    KeyHandler secretKeyManagers[] = null;
    Vector pubkm = new Vector();
    Vector seckm = new Vector();

    // load base key managers
    pubkm.add(new OpenPGPPublicKeyring(
            configData.getSetting("keymanager.openpgp.primary.pubring", "pubring.pgp"), null));
    seckm.add(new OpenPGPPublicKeyring(
            configData.getSetting("keymanager.openpgp.primary.secring", "secring.pgp"), null));

    // load extra key managers
    KeyHandler[] tmp = KeyHandler.loadKeysourceList(configData, "keymanager.openpgp.publiclist.");
    if (tmp != null) {
        for (int n = 0; n < tmp.length; n++)
            pubkm.add(tmp[n]);
    }

    tmp = KeyHandler.loadKeysourceList(configData, "keymanager.openpgp.secretlist.");
    if (tmp != null) {
        for (int n = 0; n < tmp.length; n++)
            seckm.add(tmp[n]);
    }

    // store in arrays
    publicKeyManagers = new KeyHandler[pubkm.size()];
    for (int n = 0; n < publicKeyManagers.length; n++)
        publicKeyManagers[n] = (KeyHandler) pubkm.elementAt(n);

    secretKeyManagers = new KeyHandler[seckm.size()];
    for (int n = 0; n < secretKeyManagers.length; n++)
        secretKeyManagers[n] = (KeyHandler) seckm.elementAt(n);

    // create email processor
    h = new OpenPGPHandler(symmetricAlgorithm);

    // process email

    FileInputStream in = new FileInputStream(file);
    byte[] email1_dat = new byte[in.available()];
    in.read(email1_dat);
    in.close();

    System.err.println("Parsing...");
    Email email1 = new Email(email1_dat);

    System.err.println("Processing...");

    boolean retry;

    do {

        retry = false;

        try {
            email1 = h.processIncomingMail(publicKeyManagers, secretKeyManagers, email1, passPhrases);
        } catch (ChecksumFailureException cfe) {

            retry = true;

            System.err.print("Passphrase required: ");

            String inputLine;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

            inputLine = br.readLine();
            PassPhrase p = new PassPhrase(inputLine.getBytes());
            addPassphrase(p);
        }
    } while (retry);

    System.out.println(new String(email1.getBytes()));

}

From source file:debug.PGPSecretKeyringParser.java

License:Open Source License

/**
 * @param args the command line arguments
 *///from  w w w  . ja v a2  s.co m
public static void main(String[] args) {
    debug.Debug.setLevel(1); // set default debug verbosity

    if (args.length == 0) {
        System.out.println("PGPSecretKeyringParser - PGP Secret key viewer " + version + " : By Marcus Povey");
        System.out.println();
        System.out.println("Usage: java test.PGPSecretKeyringParser <filename>");
    } else {
        try {

            // generate and write demo packet.
            System.out.println("Adding Bouncy Castle JCE provider...");
            Security.addProvider(new BouncyCastleProvider());

            System.out.println("Opening packet stream to " + args[0] + "...");
            OpenPGPPacketInputStream in = new OpenPGPPacketInputStream(new FileInputStream(args[0]));

            System.out.println("Reading packet stream...");
            int n = 1;

            Packet p = null;
            do {

                p = in.readPacket();

                if (p != null) {
                    System.out.print("Packet " + n + ": ");
                    System.out.print("Type " + p.getPacketHeader().getType());
                    if (p.getPacketHeader().isNewFormat())
                        System.out.print(" (New Format),");
                    else
                        System.out.print(",");

                    System.out.print(" Body length " + p.getPacketHeader().getBodyLength());
                    System.out.println();

                    // handle secret key
                    if (p instanceof SecretKeyPacket) {
                        SecretKeyPacket skp = (SecretKeyPacket) p;

                        System.out.println("Secret key packet detected! ");

                        if (/*(skp.getVersion() == 4) && */(PublicKeyAlgorithmSettings
                                .isRSA(skp.getAlgorithm()))) {

                            // key ID
                            System.out.print("KeyID: 0x");
                            debug.Debug.hexDump(1, skp.getKeyID());

                            // fingerprint
                            System.out.print("Fingerprint: 0x");
                            debug.Debug.hexDump(1, skp.getFingerprint());

                            // prompt for passphrase
                            System.out.print("Enter passphrase for decryption: ");

                            String inputLine;
                            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

                            inputLine = br.readLine();

                            // decrypt and output key material
                            skp.decryptKeyData(inputLine.getBytes());

                            RSAAlgorithmParameters keydata = (RSAAlgorithmParameters) skp.getKeyData();

                            debug.Debug.println(1, "Public ---------");
                            debug.Debug.println(1, "MOD: ");
                            debug.Debug.hexDump(1, keydata.getN().toByteArray());
                            debug.Debug.println(1, "EXP: ");
                            debug.Debug.hexDump(1, keydata.getE().toByteArray());

                            debug.Debug.println(1, "Private --------");
                            debug.Debug.println(1, "EXP: ");
                            debug.Debug.hexDump(1, keydata.getD().toByteArray());
                            debug.Debug.println(1, "EXP Length: " + keydata.getD().bitLength());
                            debug.Debug.println(1, "PRI: ");
                            debug.Debug.hexDump(1, keydata.getP().toByteArray());
                            debug.Debug.println(1, "PRI Length: " + keydata.getP().bitLength());
                            debug.Debug.println(1, "PRI2: ");
                            debug.Debug.hexDump(1, keydata.getQ().toByteArray());
                            debug.Debug.println(1, "PRI2 Length: " + keydata.getQ().bitLength());
                            debug.Debug.println(1, "MUI: ");
                            debug.Debug.hexDump(1, keydata.getU().toByteArray());
                            debug.Debug.println(1, "MUI Length: " + keydata.getU().bitLength());
                        } else {
                            System.out.println("Sorry, only v4 keys are currently supported...");
                        }
                    }
                }

                n++;
            } while (p != null);

            System.out.println("Closing stream...");
            in.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:decrypt12.decrypt12.java

public static void decrypt(String KeyFile, String C12File, String SQLFile) throws Exception {

    final File tempFile = new File(System.getProperty("java.io.tmpdir") + "/"
            + (int) (System.currentTimeMillis() / 1000L) + "-msgstore.enc");

    if (!new File(KeyFile).isFile())
        quit("The specified input key file does not exist.");

    else if (new File(KeyFile).length() != 158)
        quit("The specified input key file is invalid.");

    else if (!new File(C12File).isFile())
        quit("The specified input crypt12 file does not exist.");

    InputStream KeyIn = new FileInputStream(KeyFile);
    InputStream WdbIn = new BufferedInputStream(new FileInputStream(C12File));

    byte[] KeyData = new byte[158];
    KeyIn.read(KeyData);//w  ww  .j  a v  a  2s.com
    byte[] T1 = new byte[32];
    System.arraycopy(KeyData, 30, T1, 0, 32);
    byte[] KEY = new byte[32];
    System.arraycopy(KeyData, 126, KEY, 0, 32);
    KeyIn.close();

    byte[] C12Data = new byte[67];
    WdbIn.read(C12Data);
    byte[] T2 = new byte[32];
    System.arraycopy(C12Data, 3, T2, 0, 32);
    byte[] IV = new byte[16];
    System.arraycopy(C12Data, 51, IV, 0, 16);

    if (!new String(T1, 0, T1.length, "ASCII").equals(new String(T2, 0, T2.length, "ASCII")))
        quit("Key file mismatch or crypt12 file is corrupt.");

    int InputLength = WdbIn.available();
    RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");

    byte[] tempBuffer = new byte[1024];
    int I;

    while ((I = WdbIn.read(tempBuffer)) != -1)
        raf.write(tempBuffer, 0, I);
    raf.setLength(InputLength - 20);
    raf.close();
    WdbIn.close();

    InputStream PdbSt = new BufferedInputStream(new FileInputStream(tempFile));

    Cipher cipher;
    Security.addProvider(new BouncyCastleProvider());
    cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC"); // BouncyCastle
    // cipher = Cipher.getInstance("AES/GCM/NoPadding", "SC"); // SpongyCastle (Android)

    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY, "AES"), new IvParameterSpec(IV));
    CipherInputStream CipherStream = new CipherInputStream(PdbSt, cipher);

    InflaterInputStream CryptOutput = new InflaterInputStream(CipherStream, new Inflater(false));

    try {
        FileOutputStream InflateBuffer = new FileOutputStream(SQLFile);
        int N = 0;
        byte[] CryptBuffer = new byte[8192];

        while ((N = CryptOutput.read(CryptBuffer)) != -1) {
            InflateBuffer.write(CryptBuffer, 0, N);
        }
        InflateBuffer.close();

    } catch (IOException ex) {
        quit("Fatal error:" + ex);
    }

    CipherStream.close();
    tempFile.delete();

    InputStream SqlDB = new FileInputStream(SQLFile);

    byte[] SqlData = new byte[6];
    SqlDB.read(SqlData);
    byte[] MS = new byte[6];
    System.arraycopy(SqlData, 0, MS, 0, 6);
    SqlDB.close();

    if (!new String(MS, 0, MS.length, "ASCII").toLowerCase().equals("sqlite")) {
        new File(SQLFile).delete();
        quit("Decryption of crypt12 file has failed.");
    }

    else
        quit("Decryption of crypt12 file was successful.");
}