Example usage for org.bouncycastle.crypto AsymmetricBlockCipher processBlock

List of usage examples for org.bouncycastle.crypto AsymmetricBlockCipher processBlock

Introduction

In this page you can find the example usage for org.bouncycastle.crypto AsymmetricBlockCipher processBlock.

Prototype

public byte[] processBlock(byte[] in, int inOff, int len) throws InvalidCipherTextException;

Source Link

Document

process the block of len bytes stored in in from offset inOff.

Usage

From source file:bluecrystal.service.service.SignVerifyService.java

License:Open Source License

public boolean verify(int hashId, byte[] contentHash, byte[] sigBytes, X509Certificate cert) throws Exception {
    RSAPublicKey pubK = (RSAPublicKey) cert.getPublicKey();
    CipherParameters param = new RSAKeyParameters(false, pubK.getModulus(), pubK.getPublicExponent());
    RSABlindedEngine cipher2 = new RSABlindedEngine();
    cipher2.init(false, param);//w w  w.j a  v a  2 s .  com
    AsymmetricBlockCipher cipher = new PKCS1Encoding(cipher2);
    byte[] sig = cipher.processBlock(sigBytes, 0, sigBytes.length);
    AlgorithmIdentifier algId = createAlgorithm(hashId);
    byte[] expected = derEncode(contentHash, algId);

    LOG.debug("Sig:(" + sigBytes.length + ")" + Utils.conv(sigBytes));
    LOG.debug("Has:(" + contentHash.length + ")" + Utils.conv(contentHash));
    LOG.debug("Sig:(" + sig.length + ")" + Utils.conv(sig));
    LOG.debug("Exp:(" + expected.length + ")" + Utils.conv(expected));

    if (sig.length == expected.length) {
        for (int i = 0; i < sig.length; i++) {
            if (sig[i] != expected[i]) {
                return false;
            }
        }
    } else if (sig.length == expected.length - 2) // NULL left out
    {
        int sigOffset = sig.length - contentHash.length - 2;
        int expectedOffset = expected.length - contentHash.length - 2;

        expected[1] -= 2; // adjust lengths
        expected[3] -= 2;

        for (int i = 0; i < contentHash.length; i++) {
            if (sig[sigOffset + i] != expected[expectedOffset + i]) // check hash
            {
                return false;
            }
        }

        for (int i = 0; i < sigOffset; i++) {
            if (sig[i] != expected[i]) // check header less NULL
            {
                return false;
            }
        }
    } else {
        return false;
    }

    return true;

}

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;/* w  w w. ja  va2  s  .co m*/
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data//from   w  w w  .  j ava  2 s.  com
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}

From source file:com.foilen.smalltools.crypt.AbstractAsymmetricBlockCipherCrypt.java

License:Open Source License

/**
 * Encrypt/Decrypt the data with the specified key.
 * /*from  ww w . ja  va2s  .  co m*/
 * @param key
 *            the key
 * @param in
 *            the data to encrypt/decrypt
 * @param crypt
 *            true to encrypt;false to decrypt
 * @return the encrypted/decrypted data
 */
private byte[] process(AsymmetricKeyParameter key, byte[] in, boolean crypt) {

    log.debug("process() crypt {}  in.length {}", crypt, in.length);

    try {

        // Prepare cipher
        AsymmetricBlockCipher asymmetricBlockCipher = generateAsymmetricBlockCipher();
        asymmetricBlockCipher.init(crypt, key);

        // Process
        return asymmetricBlockCipher.processBlock(in, 0, in.length);

    } catch (Exception e) {
        throw new SmallToolsException("Could not process", e);
    }
}

From source file:com.foilen.smalltools.crypt.bouncycastle.asymmetric.AbstractAsymmetricBlockCipherCrypt.java

License:Open Source License

/**
 * Encrypt/Decrypt the data with the specified key.
 *
 * @param key/*  w w w  .  j a v a 2  s . co  m*/
 *            the key
 * @param in
 *            the data to encrypt/decrypt
 * @param crypt
 *            true to encrypt;false to decrypt
 * @return the encrypted/decrypted data
 */
private byte[] process(AsymmetricKeyParameter key, byte[] in, boolean crypt) {

    log.debug("process() crypt {} in.length {}", crypt, in.length);

    try {

        // Prepare cipher
        AsymmetricBlockCipher asymmetricBlockCipher = generateAsymmetricBlockCipher();
        asymmetricBlockCipher.init(crypt, key);

        // Process
        return asymmetricBlockCipher.processBlock(in, 0, in.length);

    } catch (Exception e) {
        throw new SmallToolsException("Could not process", e);
    }
}

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

/**
 * Encrypt data using RSA.//  w ww.  ja v a2s  .  c  o m
 * CAUTION: this can take a while on large data
 * 
 * @param key RSA key to use for encryption
 * @param data Cleartext data
 * @return The ciphertext data or null if an error occured
 */
public static byte[] encryptRSA(Key key, byte[] data) {
    //
    // Get an RSA Cipher instance
    //
    //Cipher rsa = null;

    try {
        /* The following commented code can be used the BouncyCastle
         * JCE provider signature is intact, which is not the
         * case when BC has been repackaged using jarjar
        rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        rsa.init (Cipher.ENCRYPT_MODE, key, CryptoHelper.sr);                   
        return rsa.doFinal(data);
        */
        AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine());
        if (key instanceof RSAPublicKey) {
            c.init(true, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(),
                    ((RSAPublicKey) key).getPublicExponent()));
        } else if (key instanceof RSAPrivateKey) {
            c.init(true, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(),
                    ((RSAPrivateKey) key).getPrivateExponent()));
        } else {
            return null;
        }

        int insize = c.getInputBlockSize();

        int offset = 0;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while (offset < data.length) {
            int len = Math.min(insize, data.length - offset);
            baos.write(c.processBlock(data, offset, len));
            offset += len;
        }

        return baos.toByteArray();

        /*
            } catch (NoSuchProviderException nspe) {
              return null;
            } catch (NoSuchPaddingException nspe) {
              return null;
            } catch (NoSuchAlgorithmException nsae) {
              return null;
            } catch (InvalidKeyException ike) {
              return null;
            } catch (BadPaddingException bpe) {
              return null;
            } catch (IllegalBlockSizeException ibse) {
              return null;
            }
        */
    } catch (InvalidCipherTextException icte) {
        return null;
    } catch (IOException ioe) {
        return null;
    }
}

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

/**
 * Decrypt data previously encrypted with RSA
 * @param key RSA key to use for decryption
 * @param data Ciphertext data/*w w  w .jav a 2  s .  c  om*/
 * @return The cleartext data or null if an error occurred
 */
public static byte[] decryptRSA(Key key, byte[] data) {
    //
    // Get an RSA Cipher instance
    //

    //Cipher rsa = null;

    try {
        /* The following commented code can be used the BouncyCastle
         * JCE provider signature is intact, which is not the
         * case when BC has been repackaged using jarjar
        rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        rsa.init (Cipher.DECRYPT_MODE, key, CryptoHelper.sr);
        return rsa.doFinal(data);
        */

        AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine());
        if (key instanceof RSAPublicKey) {
            c.init(false, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(),
                    ((RSAPublicKey) key).getPublicExponent()));
        } else if (key instanceof RSAPrivateKey) {
            c.init(false, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(),
                    ((RSAPrivateKey) key).getPrivateExponent()));
        } else {
            return null;
        }

        int insize = c.getInputBlockSize();

        int offset = 0;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while (offset < data.length) {
            int len = Math.min(insize, data.length - offset);
            baos.write(c.processBlock(data, offset, len));
            offset += len;
        }

        return baos.toByteArray();

        /*
            } catch (NoSuchProviderException nspe) {
              return null;
            } catch (NoSuchPaddingException nspe) {
              return null;
            } catch (NoSuchAlgorithmException nsae) {
              return null;
            } catch (InvalidKeyException ike) {
              return null;
            } catch (BadPaddingException bpe) {
              return null;
            } catch (IllegalBlockSizeException ibse) {
              return null;
            }
        */
    } catch (InvalidCipherTextException icte) {
        return null;
    } catch (IOException ioe) {
        return null;
    }
}

From source file:com.maiereni.util.EncryptedFileLoader.java

License:Apache License

/**
 * Encrypt and encode /*w w  w .j  a  v  a2s .c  o  m*/
 * @param buffer
 * @return
 * @throws Exception
 */
protected byte[] encryptRSA(final byte[] buffer) throws Exception {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        AsymmetricBlockCipher cipher = getAsymmetricBlockCipher(true);
        int len = cipher.getInputBlockSize();
        for (int i = 0; i < buffer.length; i += len) {
            if (i + len > buffer.length)
                len = buffer.length - i;

            byte[] encrypted = cipher.processBlock(buffer, i, len);
            out.write(encrypted);
        }
        return out.toByteArray();
    }
}

From source file:com.maiereni.util.EncryptedFileLoader.java

License:Apache License

protected byte[] decryptRSA(final byte[] buffer) throws Exception {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        AsymmetricBlockCipher cipher = getAsymmetricBlockCipher(false);
        int len = cipher.getInputBlockSize();
        for (int i = 0; i < buffer.length; i += len) {
            if (i + len > buffer.length) {
                len = buffer.length - i;
            }//from w  ww.j  a  v  a  2 s.  co  m

            byte[] decrypted = cipher.processBlock(buffer, i, len);
            out.write(decrypted);
        }
        return out.toByteArray();
    }
}

From source file:com.oth.jasds.crypto.Crypto.java

@Override
public String encryptFileKey(byte[] fileKey, PublicKey pubKey) {
    try {/*from   ww  w  .j av a2  s .co m*/
        AsymmetricBlockCipher e = new RSAEngine();
        e = new PKCS1Encoding(e);
        AsymmetricKeyParameter pub = (AsymmetricKeyParameter) PublicKeyFactory.createKey(pubKey.getEncoded());
        e.init(true, pub);
        byte[] encFk = e.processBlock(fileKey, 0, fileKey.length);
        BASE64Encoder b64 = new BASE64Encoder();
        return b64.encode(encFk);

    } catch (IOException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidCipherTextException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}