Search in sources :

Example 36 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project keystore-explorer by kaikramer.

the class Pkcs10Util method generateCsr.

/**
 * Create a PKCS #10 certificate signing request (CSR) using the supplied
 * certificate, private key and signature algorithm.
 *
 * @param cert
 *            The certificate
 * @param privateKey
 *            The private key
 * @param signatureType
 *            Signature
 * @param challenge
 *            Challenge, optional, pass null if not required
 * @param unstructuredName
 *            An optional company name, pass null if not required
 * @param useExtensions
 *            Use extensions from cert for extensionRequest attribute?
 * @throws CryptoException
 *             If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
    try {
        JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
        // add challenge attribute
        if (challenge != null) {
            // PKCS#9 2.0: SHOULD use UTF8String encoding
            csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
        }
        if (unstructuredName != null) {
            csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
        }
        if (useExtensions) {
            // add extensionRequest attribute with all extensions from the certificate
            Certificate certificate = Certificate.getInstance(cert.getEncoded());
            Extensions extensions = certificate.getTBSCertificate().getExtensions();
            if (extensions != null) {
                csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
            }
        }
        // fall back to bouncy castle provider if given provider does not support the requested algorithm
        if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
            provider = new BouncyCastleProvider();
        }
        ContentSigner contentSigner = null;
        if (provider == null) {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
        } else {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
        }
        PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
        if (!verifyCsr(csr)) {
            throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
        }
        return csr;
    } catch (CertificateEncodingException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateEncodingException(java.security.cert.CertificateEncodingException) Extensions(org.bouncycastle.asn1.x509.Extensions) CryptoException(org.kse.crypto.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 37 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project keystore-explorer by kaikramer.

the class Spkac method decodeSpkac.

private void decodeSpkac(byte[] der) throws SpkacException {
    try {
        ASN1Sequence signedPublicKeyAndChallenge = ASN1Sequence.getInstance(der);
        ASN1Sequence publicKeyAndChallenge = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(0);
        ASN1Sequence signatureAlgorithm = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(1);
        DERBitString signature = (DERBitString) signedPublicKeyAndChallenge.getObjectAt(2);
        ASN1ObjectIdentifier signatureAlgorithmOid = (ASN1ObjectIdentifier) signatureAlgorithm.getObjectAt(0);
        ASN1Sequence spki = (ASN1Sequence) publicKeyAndChallenge.getObjectAt(0);
        DERIA5String challenge = (DERIA5String) publicKeyAndChallenge.getObjectAt(1);
        ASN1Sequence publicKeyAlgorithm = (ASN1Sequence) spki.getObjectAt(0);
        DERBitString publicKey = (DERBitString) spki.getObjectAt(1);
        ASN1ObjectIdentifier publicKeyAlgorithmOid = (ASN1ObjectIdentifier) publicKeyAlgorithm.getObjectAt(0);
        ASN1Primitive algorithmParameters = publicKeyAlgorithm.getObjectAt(1).toASN1Primitive();
        this.challenge = challenge.getString();
        this.publicKey = decodePublicKeyFromBitString(publicKeyAlgorithmOid, algorithmParameters, publicKey);
        this.signatureAlgorithm = getSignatureAlgorithm(signatureAlgorithmOid);
        this.signature = signature.getBytes();
    } catch (Exception ex) {
        throw new SpkacException(res.getString("NoDecodeSpkac.exception.message"), ex);
    }
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException)

Example 38 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project keystore-explorer by kaikramer.

the class JarSigner method createSignatureBlock.

private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException {
    try {
        List<X509Certificate> certList = new ArrayList<>();
        Collections.addAll(certList, certificateChain);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
        JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()).setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
        if (provider != null) {
            csb.setProvider(provider);
        }
        JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);
        // remove cmsAlgorithmProtect for compatibility reasons
        SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
        final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
        sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {

            @Override
            public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
                AttributeTable ret = sAttrGen.getAttributes(parameters);
                return ret.remove(CMSAttributes.cmsAlgorithmProtect);
            }
        }, sigGen.getUnsignedAttributeTableGenerator());
        CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
        dataGen.addSignerInfoGenerator(sigGen);
        dataGen.addCertificates(new JcaCertStore(certList));
        CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);
        // now let TSA time-stamp the signature
        if (tsaUrl != null && !tsaUrl.isEmpty()) {
            signedData = addTimestamp(tsaUrl, signedData);
        }
        return signedData.getEncoded();
    } catch (Exception ex) {
        throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) DefaultSignedAttributeTableGenerator(org.bouncycastle.cms.DefaultSignedAttributeTableGenerator) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CryptoException(org.kse.crypto.CryptoException) IOException(java.io.IOException) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CMSAttributeTableGenerator(org.bouncycastle.cms.CMSAttributeTableGenerator) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CryptoException(org.kse.crypto.CryptoException) Map(java.util.Map)

Example 39 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xades4j by luisgoncalves.

the class DefaultTimeStampVerificationProvider method verifyToken.

@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput) throws TimeStampTokenVerificationException {
    TimeStampToken tsToken;
    try {
        ASN1InputStream asn1is = new ASN1InputStream(timeStampToken);
        ContentInfo tsContentInfo = ContentInfo.getInstance(asn1is.readObject());
        asn1is.close();
        tsToken = new TimeStampToken(tsContentInfo);
    } catch (IOException ex) {
        throw new TimeStampTokenStructureException("Error parsing encoded token", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenStructureException("Invalid token", ex);
    }
    X509Certificate tsaCert = null;
    try {
        /* Validate the TSA certificate */
        LinkedList<X509Certificate> certs = new LinkedList<X509Certificate>();
        for (Object certHolder : tsToken.getCertificates().getMatches(new AllCertificatesSelector())) {
            certs.add(this.x509CertificateConverter.getCertificate((X509CertificateHolder) certHolder));
        }
        ValidationData vData = this.certificateValidationProvider.validate(x509CertSelectorConverter.getCertSelector(tsToken.getSID()), tsToken.getTimeStampInfo().getGenTime(), certs);
        tsaCert = vData.getCerts().get(0);
    } catch (CertificateException ex) {
        throw new TimeStampTokenVerificationException(ex.getMessage(), ex);
    } catch (XAdES4jException ex) {
        throw new TimeStampTokenTSACertException("cannot validate TSA certificate", ex);
    }
    try {
        tsToken.validate(this.signerInfoVerifierBuilder.build(tsaCert));
    } catch (TSPValidationException ex) {
        throw new TimeStampTokenSignatureException("Invalid token signature or certificate", ex);
    } catch (Exception ex) {
        throw new TimeStampTokenVerificationException("Error when verifying the token signature", ex);
    }
    org.bouncycastle.tsp.TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo();
    try {
        String digestAlgUri = uriForDigest(tsTokenInfo.getMessageImprintAlgOID());
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        if (!Arrays.equals(md.digest(tsDigestInput), tsTokenInfo.getMessageImprintDigest())) {
            throw new TimeStampTokenDigestException();
        }
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenVerificationException("The token's digest algorithm is not supported", ex);
    }
    return tsTokenInfo.getGenTime();
}
Also used : CertificateException(java.security.cert.CertificateException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) MessageDigest(java.security.MessageDigest) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ValidationData(xades4j.providers.ValidationData) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken)

Example 40 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.

the class ProfileConfCreatorDemo method createBiometricInfo.

// method createQcStatements
private static ExtensionValueType createBiometricInfo() {
    BiometricInfo extValue = new BiometricInfo();
    // type
    // predefined image (0)
    BiometricTypeType type = new BiometricTypeType();
    extValue.getType().add(type);
    IntWithDescType predefined = new IntWithDescType();
    predefined.setValue(0);
    predefined.setDescription("image");
    type.setPredefined(predefined);
    // predefined handwritten-signature(1)
    type = new BiometricTypeType();
    predefined = new IntWithDescType();
    predefined.setValue(1);
    predefined.setDescription("handwritten-signature");
    type.setPredefined(predefined);
    extValue.getType().add(type);
    // OID
    type = new BiometricTypeType();
    type.setOid(createOidType(new ASN1ObjectIdentifier("1.2.3.4.5.6"), "dummy biometric type"));
    extValue.getType().add(type);
    // hash algorithm
    HashAlgo[] hashAlgos = new HashAlgo[] { HashAlgo.SHA256, HashAlgo.SHA384 };
    for (HashAlgo hashAlgo : hashAlgos) {
        extValue.getHashAlgorithm().add(createOidType(hashAlgo.getOid(), hashAlgo.getName()));
    }
    extValue.setIncludeSourceDataUri(TripleState.REQUIRED);
    return createExtensionValueType(extValue);
}
Also used : BiometricInfo(org.xipki.ca.certprofile.x509.jaxb.BiometricInfo) BiometricTypeType(org.xipki.ca.certprofile.x509.jaxb.BiometricTypeType) HashAlgo(org.xipki.security.HashAlgo) IntWithDescType(org.xipki.ca.certprofile.x509.jaxb.IntWithDescType) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

IOException (java.io.IOException)58 DERIA5String (org.bouncycastle.asn1.DERIA5String)36 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)31 DERBitString (org.bouncycastle.asn1.DERBitString)31 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)30 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)30 InvalidKeyException (java.security.InvalidKeyException)28 X509Certificate (java.security.cert.X509Certificate)28 SignatureException (java.security.SignatureException)27 DERSequence (org.bouncycastle.asn1.DERSequence)26 PublicKey (java.security.PublicKey)25 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)23 DEROctetString (org.bouncycastle.asn1.DEROctetString)22 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)22 Signature (java.security.Signature)21 CertificateException (java.security.cert.CertificateException)21 BigInteger (java.math.BigInteger)20 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)18 NoSuchProviderException (java.security.NoSuchProviderException)16