Search in sources :

Example 1 with Request

use of org.bouncycastle.asn1.ocsp.Request in project OpenAttestation by OpenAttestation.

the class CertificateRepository method create.

@Override
public //    @RequiresPermissions("tag_certificates:create") 
void create(Certificate item) {
    log.debug("Certificate:Create - Got request to create a new Certificate {}.", item.getId().toString());
    CertificateLocator locator = new CertificateLocator();
    locator.id = item.getId();
    try (CertificateDAO dao = TagJdbi.certificateDao()) {
        Certificate newCert = dao.findById(item.getId());
        if (newCert == null) {
            newCert = Certificate.valueOf(item.getCertificate());
            dao.insert(item.getId(), newCert.getCertificate(), newCert.getSha1().toHexString(), newCert.getSha256().toHexString(), newCert.getSubject(), newCert.getIssuer(), newCert.getNotBefore(), newCert.getNotAfter());
            log.debug("Certificate:Create - Created the Certificate {} successfully.", item.getId().toString());
        } else {
            log.error("Certificate:Create - Certificate {} will not be created since a duplicate Certificate already exists.", item.getId().toString());
            throw new RepositoryCreateConflictException(locator);
        }
    } catch (RepositoryException re) {
        throw re;
    } catch (Exception ex) {
        log.error("Certificate:Create - Error during certificate creation.", ex);
        throw new RepositoryCreateException(ex, locator);
    }
    //Store tag values from Certificate
    try {
        log.info("Tags from certificate will now be stored");
        KvAttributeRepository repository = new KvAttributeRepository();
        KvAttribute kvAttrib = new KvAttribute();
        if (kvAttrib == null || repository == null)
            log.debug("kvAttrib or repository Obj is null, unable to store certificate tags");
        else {
            List<Attribute> certAttributes = X509AttributeCertificate.valueOf(item.getCertificate()).getAttribute();
            for (Attribute attr : certAttributes) {
                for (ASN1Encodable value : attr.getAttributeValues()) {
                    if (attr.getAttrType().toString().equals(UTF8NameValueMicroformat.OID)) {
                        UTF8NameValueMicroformat microformat = new UTF8NameValueMicroformat(DERUTF8String.getInstance(value));
                        // Check if that tag with same value already exists
                        KvAttributeFilterCriteria criteria = new KvAttributeFilterCriteria();
                        criteria.nameEqualTo = microformat.getName();
                        criteria.valueEqualTo = microformat.getValue();
                        KvAttributeCollection results = repository.search(criteria);
                        if (results.getDocuments().isEmpty()) {
                            kvAttrib.setId(new UUID());
                            kvAttrib.setName(microformat.getName());
                            kvAttrib.setValue(microformat.getValue());
                            repository.create(kvAttrib);
                        } else
                            log.debug("Tag with Name:{} & Value:{} is already stored.", microformat.getName(), microformat.getValue());
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Certificate:Create - Error during attribute scan", e);
    }
}
Also used : CertificateLocator(com.intel.mtwilson.datatypes.CertificateLocator) CertificateDAO(com.intel.mtwilson.tag.dao.jdbi.CertificateDAO) KvAttribute(com.intel.mtwilson.datatypes.KvAttribute) Attribute(org.bouncycastle.asn1.x509.Attribute) KvAttribute(com.intel.mtwilson.datatypes.KvAttribute) RepositoryException(com.intel.mtwilson.tag.repository.RepositoryException) RepositoryCreateConflictException(com.intel.mtwilson.tag.repository.RepositoryCreateConflictException) RepositoryCreateException(com.intel.mtwilson.tag.repository.RepositoryCreateException) RepositoryDeleteException(com.intel.mtwilson.tag.repository.RepositoryDeleteException) RepositoryStoreException(com.intel.mtwilson.tag.repository.RepositoryStoreException) RepositoryStoreConflictException(com.intel.mtwilson.tag.repository.RepositoryStoreConflictException) RepositoryRetrieveException(com.intel.mtwilson.tag.repository.RepositoryRetrieveException) RepositoryException(com.intel.mtwilson.tag.repository.RepositoryException) RepositorySearchException(com.intel.mtwilson.tag.repository.RepositorySearchException) RepositoryCreateConflictException(com.intel.mtwilson.tag.repository.RepositoryCreateConflictException) KvAttributeCollection(com.intel.mtwilson.datatypes.KvAttributeCollection) KvAttributeRepository(com.intel.mtwilson.tag.repository.KvAttributeRepository) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) KvAttributeFilterCriteria(com.intel.mtwilson.datatypes.KvAttributeFilterCriteria) UUID(com.intel.mtwilson.util.io.UUID) UTF8NameValueMicroformat(com.intel.mtwilson.datatypes.UTF8NameValueMicroformat) Certificate(com.intel.mtwilson.datatypes.Certificate) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate) RepositoryCreateException(com.intel.mtwilson.tag.repository.RepositoryCreateException)

Example 2 with Request

use of org.bouncycastle.asn1.ocsp.Request in project nhin-d by DirectProject.

the class CertGenerator method createCertFromCSR.

public static X509Certificate createCertFromCSR(PKCS10CertificationRequest certReq, CertCreateFields signerCert) throws Exception {
    certReq.verify();
    final CertificationRequestInfo reqInfo = certReq.getCertificationRequestInfo();
    final X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    final Calendar start = Calendar.getInstance();
    final Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 3);
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    // issuer is the parent cert
    v1CertGen.setIssuerDN(signerCert.getSignerCert().getSubjectX500Principal());
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    v1CertGen.setSubjectDN(new X509Principal(reqInfo.getSubject().toString()));
    v1CertGen.setPublicKey(certReq.getPublicKey());
    v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    final ASN1Set attributesAsn1Set = reqInfo.getAttributes();
    X509Extensions certificateRequestExtensions = null;
    for (int i = 0; i < attributesAsn1Set.size(); ++i) {
        // There should be only only one attribute in the set. (that is, only
        // the `Extension Request`, but loop through to find it properly)
        final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
        if (derEncodable instanceof DERSequence) {
            final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));
            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // The `Extension Request` attribute is present.
                final ASN1Set attributeValues = attribute.getAttrValues();
                // Assume that it is the first value of the set.
                if (attributeValues.size() >= 1) {
                    certificateRequestExtensions = new X509Extensions((ASN1Sequence) attributeValues.getObjectAt(0));
                // No need to search any more.
                //break;
                }
            }
        }
    }
    @SuppressWarnings("unchecked") Enumeration<DERObjectIdentifier> oids = certificateRequestExtensions.oids();
    while (oids.hasMoreElements()) {
        DERObjectIdentifier oid = oids.nextElement();
        X509Extension ex = certificateRequestExtensions.getExtension(oid);
        v1CertGen.addExtension(oid, ex.isCritical(), X509Extension.convertValueToObject(ex));
    }
    return v1CertGen.generate((PrivateKey) signerCert.getSignerKey(), CryptoExtensions.getJCEProviderName());
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.cms.Attribute) X509Extension(org.bouncycastle.asn1.x509.X509Extension) Calendar(java.util.Calendar) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) X509Principal(org.bouncycastle.jce.X509Principal) DEREncodable(org.bouncycastle.asn1.DEREncodable)

Example 3 with Request

use of org.bouncycastle.asn1.ocsp.Request in project XobotOS by xamarin.

the class PKCS10CertificationRequest method verify.

/**
     * verify the request using the passed in public key and the provider..
     */
public boolean verify(PublicKey pubKey, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    Signature sig;
    try {
        if (provider == null) {
            sig = Signature.getInstance(getSignatureName(sigAlgId));
        } else {
            sig = Signature.getInstance(getSignatureName(sigAlgId), provider);
        }
    } catch (NoSuchAlgorithmException e) {
        //
        if (oids.get(sigAlgId.getObjectId()) != null) {
            String signatureAlgorithm = (String) oids.get(sigAlgId.getObjectId());
            if (provider == null) {
                sig = Signature.getInstance(signatureAlgorithm);
            } else {
                sig = Signature.getInstance(signatureAlgorithm, provider);
            }
        } else {
            throw e;
        }
    }
    setSignatureParameters(sig, sigAlgId.getParameters());
    sig.initVerify(pubKey);
    try {
        sig.update(reqInfo.getEncoded(ASN1Encodable.DER));
    } catch (Exception e) {
        throw new SignatureException("exception encoding TBS cert request - " + e);
    }
    return sig.verify(sigBits.getBytes());
}
Also used : Signature(java.security.Signature) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DERBitString(org.bouncycastle.asn1.DERBitString) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) GeneralSecurityException(java.security.GeneralSecurityException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 4 with Request

use of org.bouncycastle.asn1.ocsp.Request in project poi by apache.

the class PkiTestUtils method createOcspResp.

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
    // request
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);
    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);
    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }
    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
    }
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
    return ocspResp;
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 5 with Request

use of org.bouncycastle.asn1.ocsp.Request in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof KeyPair) {
        return createPemObject(((KeyPair) o).getPrivate());
    } else if (o instanceof PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Object.fromByteArray(((Key) o).getEncoded()));
        if (o instanceof RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else if (o instanceof DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (((PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509V2AttributeCertificate) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    return new PemObject(type, encoding);
}
Also used : X509CRL(java.security.cert.X509CRL) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509V2AttributeCertificate(org.bouncycastle.x509.X509V2AttributeCertificate) X509Certificate(java.security.cert.X509Certificate) PemObject(org.bouncycastle.util.io.pem.PemObject) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey)

Aggregations

IOException (java.io.IOException)53 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)31 Date (java.util.Date)30 X509Certificate (java.security.cert.X509Certificate)26 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 BigInteger (java.math.BigInteger)25 PKIMessage (org.bouncycastle.asn1.cmp.PKIMessage)22 CertificateException (java.security.cert.CertificateException)20 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)20 DERIA5String (org.bouncycastle.asn1.DERIA5String)18 X500Name (org.bouncycastle.asn1.x500.X500Name)18 ArrayList (java.util.ArrayList)17 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)17 Extensions (org.bouncycastle.asn1.x509.Extensions)17 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)17 Extension (org.bouncycastle.asn1.x509.Extension)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 PKIBody (org.bouncycastle.asn1.cmp.PKIBody)13 GeneralName (org.bouncycastle.asn1.x509.GeneralName)13