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:com.computersecurity.hybridcryptography.model.moduleDES.DESBaseCBC.java

public DESBaseCBC(int rounds) {
    try {/*  w  w w .j a va2  s.c  om*/
        Security.addProvider(new BouncyCastleProvider());
        this.rounds = rounds;
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        secureRand = SecureRandom.getInstance("SHA1PRNG");
        secureRand.nextBytes(new byte[cipher.getBlockSize()]);
        ivParamSpec = new IvParameterSpec(new byte[cipher.getBlockSize()]);

    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException ex) {

        System.out.println(ex);

    }

}

From source file:com.computersecurity.hybridcryptography.model.moduleVEA.VEABaseCBC.java

public VEABaseCBC() {
    try {/* w ww . j  av  a 2  s . com*/
        Security.addProvider(new BouncyCastleProvider());
        rounds = 16;
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        secureRand = SecureRandom.getInstance("SHA1PRNG");
        secureRand.nextBytes(new byte[cipher.getBlockSize()]);
        ivParamSpec = new IvParameterSpec(new byte[cipher.getBlockSize()]);

    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException ex) {

        System.out.println(ex);

    }

}

From source file:com.computersecurity.hybridcryptography.model.moduleVEA.VEABaseCBC.java

public VEABaseCBC(int rounds) {
    try {// www  .  j a  v  a  2s.co m
        Security.addProvider(new BouncyCastleProvider());
        this.rounds = rounds;
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        secureRand = SecureRandom.getInstance("SHA1PRNG");
        secureRand.nextBytes(new byte[cipher.getBlockSize()]);
        ivParamSpec = new IvParameterSpec(new byte[cipher.getBlockSize()]);

    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException ex) {

        System.out.println(ex);

    }

}

From source file:com.computersecurity.hybridcryptography.model.moduleVEA.VEABaseECB.java

public VEABaseECB() {
    try {//from   w  w w.  j  a v a2s .co m
        Security.addProvider(new BouncyCastleProvider());
        rounds = 16;
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);

    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException ex) {

        System.out.println(ex);

    }

}

From source file:com.computersecurity.hybridcryptography.model.moduleVEA.VEABaseECB.java

public VEABaseECB(int rounds) {
    try {//from  w w  w. j a v a 2  s  .com
        Security.addProvider(new BouncyCastleProvider());
        this.rounds = rounds;
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);

    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException ex) {

        System.out.println(ex);

    }

}

From source file:com.cordys.coe.ac.emailio.keymanager.BCKeyManagerImpl.java

License:Apache License

/**
 * Creates a new BCKeyManagerImpl object.
 *//*w  w  w  .  ja va 2  s  . com*/
public BCKeyManagerImpl() {
    if (Security.getProvider(PROVIDER_BOUNCY_CASTLE) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
}

From source file:com.cordys.coe.test.smime.TestSendEncryptedAndSignedMessage.java

License:Apache License

/**
 * This method sends the message to the receiver.
 *
 * @throws  Exception  DOCUMENTME//w w w.j a  v a2s.  c o  m
 */
private void sendMessage() throws Exception {
    final InternetAddress[] RECEIVER_ADDRESS = new InternetAddress[] {
            new InternetAddress("outlook2007@ces70.cordys.com", "Outlook 2007 User"),
            new InternetAddress("outlookexpress@ces70.cordys.com", "Outlook Express User"),
            new InternetAddress("thunderbird@ces70.cordys.com", "Thunderbird User"),
            new InternetAddress("cordystestuser1@ces70.cordys.com", "Cordys Test User 1"),
            new InternetAddress("cordystestuser2@ces70.cordys.com", "Cordys Test User 2") };
    final InternetAddress SENDER_ADDRESS = new InternetAddress("testprogram@ces70.cordys.com",
            "Test Program User");
    String sSubject = "From test progam V1 [S&E] No r";
    boolean bDoEncryption = true;
    // String sContent = "Single line"+System.getProperty("line.separator")+"SecondLine";
    String sContent = "Single line\nSecondLine";

    // Add capabilities.
    MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();

    mailcap.addMailcap(
            "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
    mailcap.addMailcap(
            "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
    mailcap.addMailcap(
            "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
    mailcap.addMailcap(
            "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
    mailcap.addMailcap(
            "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");

    CommandMap.setDefaultCommandMap(mailcap);

    /* Add BC */
    Security.addProvider(new BouncyCastleProvider());

    /* Get the private key to sign the message with */
    ICertificateInfo certInfo = m_km.getCertificateInfo(SENDER_ADDRESS.getAddress());

    if (certInfo == null) {
        throw new Exception("cannot find private key for email address " + SENDER_ADDRESS);
    }

    /* Create the message to sign and encrypt */
    Properties props = System.getProperties();
    props.put("mail.smtp.host", "srv-nl-ces70");

    Session session = Session.getDefaultInstance(props, null);

    MimeMessage body = new MimeMessage(session);
    body.setContent(sContent, "text/plain");
    body.saveChanges();

    /* Create the SMIMESignedGenerator */
    SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    X509Certificate cert = certInfo.getX509Certificate();

    ASN1EncodableVector attributes = new ASN1EncodableVector();
    X509Name name = new X509Name(cert.getIssuerDN().getName());
    IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, cert.getSerialNumber());
    SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute(
            issuerAndSerialNumber);
    attributes.add(encryptionKeyPreferenceAttribute);
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSigner((PrivateKey) certInfo.getKey(), cert,
            "DSA".equals(certInfo.getKey().getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1
                    : SMIMESignedGenerator.DIGEST_MD5,
            new AttributeTable(attributes), null);

    /* Add the list of certs to the generator */
    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(cert);

    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    signer.addCertificatesAndCRLs(certs);

    /* Sign the message */
    MimeMultipart mm = signer.generate(body, "BC");
    MimeMessage signedMessage = new MimeMessage(session);

    /* Set the content of the signed message */
    signedMessage.setContent(mm);
    signedMessage.saveChanges();

    /* Create the encrypter */
    if (bDoEncryption) {
        SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();

        for (InternetAddress ia : RECEIVER_ADDRESS) {
            ICertificateInfo ciTemp = m_km.getCertificateInfo(ia.getAddress());

            if (ciTemp != null) {
                encrypter.addKeyTransRecipient(ciTemp.getX509Certificate());
            } else if (LOG.isDebugEnabled()) {
                LOG.debug("No certificate found for " + ia.toString());
            }
        }

        /* Encrypt the message */
        MimeBodyPart encryptedPart = encrypter.generate(signedMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC,
                "BC");

        /*
         * Create a new MimeMessage that contains the encrypted and signed content
         */
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encryptedPart.writeTo(out);

        body = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));
    } else {
        body = signedMessage;
    }

    body.setFrom(SENDER_ADDRESS);
    body.setRecipients(Message.RecipientType.TO, RECEIVER_ADDRESS);
    body.addRecipient(Message.RecipientType.TO,
            new InternetAddress("intermediate@ces70.cordys.com", "Intermediate user"));

    body.setSentDate(new Date());
    body.addHeader("User-Agent", "CordysMailClient");
    body.setSubject(sSubject);

    Transport.send(body);
}

From source file:com.cryptolib.CryptoObject.java

License:Open Source License

/** 
* Constructor.//from  w ww . j  ava2  s . com
* Create a new CryptoObject with encryption asymmetric elliptic curve encryption keypair 
* and digital sign asymmetric elliptic curve keypair.
* curve specificies elliptic curve for encryption scheme and sign algorithm e.g. "curve25519"
* enc_algorithm must be an implemented elliptic curve encryption algorithm e.g. "ECDH"
* shortAuthenticationStringSize must be a positive number, that represents the short authentication byte length.
* iv_size must be positiv, byte size of iv for encryption scheme
* tag_size must be positiv, byte size of tag for encryption scheme
*/
public CryptoObject(String curve, String enc_algorithm, int shortAuthenticationStringSize, int iv_size,
        int tag_size) throws CryptoSocketException {
    if (0 >= shortAuthenticationStringSize || 0 >= iv_size || 0 >= tag_size) {
        throw new CryptoSocketException(
                "shortAuthenticationStringSize,iv_size and tag_size must be a positive number!");
    }

    try {
        X9ECParameters ecP = CustomNamedCurves.getByName(curve);
        org.bouncycastle.jce.spec.ECParameterSpec ecGenSpec = new org.bouncycastle.jce.spec.ECParameterSpec(
                ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        this.provider = new BouncyCastleProvider();
        KeyPairGenerator g = KeyPairGenerator.getInstance(enc_algorithm, this.provider);
        this.random = new SecureRandom();
        g.initialize(ecGenSpec, this.random);
        this.encKeypair = g.generateKeyPair();

        if (this.encKeypair == null) {
            throw new CryptoSocketException("Unable to create new key pair!");
        }

        this.OOB = new byte[shortAuthenticationStringSize];
        this.random.nextBytes(this.OOB);
    } catch (NoSuchAlgorithmException nsa) {
        throw new CryptoSocketException("Algorithm is not supported!");
    } catch (InvalidAlgorithmParameterException iap) {
        throw new CryptoSocketException("Wrong parameter for algorithm!");
    }

    this.enc_algorithm = enc_algorithm;
    this.curve = curve;
    this.iv_size = iv_size;
    this.tag_size = tag_size;
}

From source file:com.cryptolib.CryptoObject.java

License:Open Source License

/**
* Open commitment and extract message to create shared secret.
*//*  www .  j a  va2 s  .  co m*/
public void openCommitmentAndCreateSharedSecret(byte[] decommitment)
        throws CryptoSocketException, InvalidKeyException, NoSuchAlgorithmException {
    this.cc.open(decommitment);

    try {
        BCECPublicKey mypk = (BCECPublicKey) (this.encKeypair.getPublic());
        int publicKeySize = mypk.getQ().getEncoded(true).length - 1;
        byte[] message = this.cc.getOtherMessage();

        if (message.length != publicKeySize + this.OOB.length) {
            throw new CryptoSocketException("Message size is wrong!");
        }

        byte[] otherPK = new byte[publicKeySize + 1];

        //compressed encoding magic byte
        otherPK[0] = (byte) 0x02;
        byte[] otherOOB = new byte[this.OOB.length];
        System.arraycopy(message, 0, otherPK, 1, publicKeySize);
        System.arraycopy(message, publicKeySize, otherOOB, 0, otherOOB.length);
        X9ECParameters ecP = CustomNamedCurves.getByName(curve);
        org.bouncycastle.jce.spec.ECParameterSpec ecGenSpec = new org.bouncycastle.jce.spec.ECParameterSpec(
                ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH());
        //ECNamedCurveParameterSpec ecP = ECNamedCurveTable.getParameterSpec(this.curve);
        ECPublicKeySpec pubKey = new ECPublicKeySpec(ecP.getCurve().decodePoint(otherPK), ecGenSpec);
        KeyFactory kf = KeyFactory.getInstance(this.enc_algorithm, new BouncyCastleProvider());
        ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKey);
        createSharedEncKey(pk);
        mergeOOB(otherOOB);
    } catch (NoSuchAlgorithmException nsa) {
        throw new CryptoSocketException("Algorithm is not supported!");
    } catch (InvalidKeySpecException iks) {
        throw new CryptoSocketException("Wrong parameter for algorithm!");
    }
}

From source file:com.datamountaineer.streamreactor.connect.coap.Server.java

License:Apache License

public Server(Integer securePort, Integer insecurePort, Integer keyport) {
    Security.addProvider(new BouncyCastleProvider());
    server = new CoapServer();
    server.add(new ObservableResource("secure"));
    server.add(new ObservableResource("insecure"));
    server.add(new ObservableResource("key"));

    secure = securePort;//from   www  . ja v  a  2 s . c om
    insecure = insecurePort;
    key = keyport;

    DTLSConnector sslConnector = getConnectorSSL(securePort);
    DTLSConnector keyConnector = getConnectorKeys(key);

    //add secure
    server.addEndpoint(new CoapEndpoint(sslConnector, NetworkConfig.getStandard()));

    //add key
    server.addEndpoint(new CoapEndpoint(keyConnector, NetworkConfig.getStandard()));

    //add unsecure
    InetSocketAddress addr = null;
    try {
        addr = new InetSocketAddress(InetAddress.getByName("localhost"), insecurePort);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    server.addEndpoint(new CoapEndpoint(addr));

    // add special interceptor for message traces
    for (Endpoint ep : server.getEndpoints()) {
        ep.addInterceptor(new MessageTracer());
    }
}