Example usage for org.bouncycastle.crypto.encodings PKCS1Encoding PKCS1Encoding

List of usage examples for org.bouncycastle.crypto.encodings PKCS1Encoding PKCS1Encoding

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.encodings PKCS1Encoding PKCS1Encoding.

Prototype

public PKCS1Encoding(AsymmetricBlockCipher cipher) 

Source Link

Document

Basic constructor.

Usage

From source file:VerifyDescriptors.java

License:Open Source License

private static boolean verifySignature(String digest, String signature, String signingKey) throws Exception {
    byte[] signatureBytes = Base64.decodeBase64(signature.substring(0 + "-----BEGIN SIGNATURE-----\n".length(),
            signature.length() - "-----END SIGNATURE-----\n".length()).replaceAll("\n", ""));
    RSAPublicKey rsaSigningKey = (RSAPublicKey) new PEMReader(new StringReader(signingKey)).readObject();
    RSAKeyParameters rsakp = new RSAKeyParameters(false, rsaSigningKey.getModulus(),
            rsaSigningKey.getPublicExponent());
    PKCS1Encoding pe = new PKCS1Encoding(new RSAEngine());
    pe.init(false, rsakp);/*  w  ww  .  jav a 2  s.  c o m*/
    byte[] decryptedSignatureDigest = pe.processBlock(signatureBytes, 0, signatureBytes.length);
    String decryptedSignatureDigestString = Hex.encodeHexString(decryptedSignatureDigest);
    return decryptedSignatureDigestString.equalsIgnoreCase(digest);
}

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);//ww  w.ja va 2s .  c o m
    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;//from  w ww .  java2  s.  c  om
    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  ww  .  ja  va 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.asymmetric.RSACrypt.java

License:Open Source License

@Override
protected AsymmetricBlockCipher generateAsymmetricBlockCipher() {
    return new PKCS1Encoding(new RSAEngine());
}

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

License:Apache License

/**
 * Encrypt data using RSA./*from   ww w  .  j ava  2s  .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/*from w ww  .  j  av  a2 s.  c o m*/
 * @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.github.chuckbuckethead.cypher.keys.RSAKey.java

License:Open Source License

/**
 * @return an RSA decryption cipher/* w w  w .  j  ava 2  s  . co  m*/
 */
protected synchronized AsymmetricBlockCipher getRSADecryptCipher() {
    if (decodeCipher == null) {
        try {
            byte[] bytes = getEncoder().decode(privateKey);
            EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bytes);

            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            PrivateKey key = keyFactory.generatePrivate(privateKeySpec);

            this.decodeCipher = new PKCS1Encoding(new RSABlindedEngine());
            decodeCipher.init(false, generatePrivateKeyParameter((RSAPrivateKey) key));
        } catch (Exception e) {
            throw new RuntimeException("Error constructing Cipher: ", e);
        }
    }

    return decodeCipher;
}

From source file:com.github.chuckbuckethead.cypher.keys.RSAKey.java

License:Open Source License

/**
 * @return/* w w w  .  jav a2s  .  c  om*/
 */
protected synchronized AsymmetricBlockCipher getRSAEncryptCipher() {
    if (encodeCipher == null) {
        try {
            byte[] bytes = getEncoder().decode(publicKey);
            EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes);

            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            PublicKey key = keyFactory.generatePublic(publicKeySpec);

            this.encodeCipher = new PKCS1Encoding(new RSABlindedEngine());
            encodeCipher.init(true, generatePublicKeyParameter((RSAPublicKey) key));
        } catch (Exception e) {
            throw new RuntimeException("Error constructing Cipher: ", e);
        }
    }

    return encodeCipher;
}

From source file:com.licel.jcardsim.crypto.AssymetricCipherImpl.java

License:Apache License

public AssymetricCipherImpl(byte algorithm) {
    this.algorithm = algorithm;
    switch (algorithm) {
    case ALG_RSA_NOPAD:
        engine = new RSAEngine();
        paddingEngine = null;/*from   ww w .j  a  v a  2  s .c om*/
        break;
    case ALG_RSA_PKCS1:
        engine = new PKCS1Encoding(new RSAEngine());
        paddingEngine = null;
        break;
    default:
        CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM);
        break;
    }
}