Search in sources :

Example 36 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project webauthn4j by webauthn4j.

the class TPMAuthenticator method createAttestationCertificate.

@Override
public X509Certificate createAttestationCertificate(AttestationStatementRequest attestationStatementRequest, AttestationOption attestationOption) {
    AttestationCertificateBuilder builder = new AttestationCertificateBuilder(getAttestationIssuerCertificate(), new X500Principal(attestationOption.getSubjectDN()), this.getAttestationKeyPair().getPublic());
    builder.addSubjectAlternativeNamesExtension("2.23.133.2.3=#0c0b69643a3030303230303030,2.23.133.2.2=#0c03535054,2.23.133.2.1=#0c0b69643a3439344535343433");
    if (attestationOption.isCAFlagInBasicConstraints()) {
        builder.addBasicConstraintsExtension();
    }
    if (attestationOption instanceof TPMAttestationOption) {
        TPMAttestationOption tpmAttestationOption = (TPMAttestationOption) attestationOption;
        if (tpmAttestationOption.isTcgKpAIKCertificateFlagInExtendedKeyUsage()) {
            builder.addExtendedKeyUsageExtension(KeyPurposeId.getInstance(new ASN1ObjectIdentifier("2.23.133.8.3")));
        }
    }
    return builder.build(this.getAttestationIssuerPrivateKey());
}
Also used : X500Principal(javax.security.auth.x500.X500Principal) AttestationCertificateBuilder(com.webauthn4j.test.AttestationCertificateBuilder) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 37 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project snowblossom by snowblossomcoin.

the class CertGen method generateSelfSignedCert.

/**
 * @param key_pair Key pair to use to sign the cert inner signed message, the node key
 * @param tls_wkp The temporary key to use just for this cert and TLS sessions
 * @param spec Address for 'key_pair'
 */
public static X509Certificate generateSelfSignedCert(WalletKeyPair key_pair, WalletKeyPair tls_wkp, AddressSpec spec) throws Exception {
    AddressSpecHash address_hash = AddressUtil.getHashForSpec(spec);
    String address = AddressUtil.getAddressString(Globals.NODE_ADDRESS_STRING, address_hash);
    byte[] encoded_pub = tls_wkp.getPublicKey().toByteArray();
    SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(encoded_pub));
    String dn = String.format("CN=%s, O=Snowblossom", address);
    X500Name issuer = new X500Name(dn);
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + 86400000L * 365L * 10L);
    X500Name subject = issuer;
    X509v3CertificateBuilder cert_builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, subjectPublicKeyInfo);
    // System.out.println(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName);
    ASN1ObjectIdentifier snow_claim_oid = new ASN1ObjectIdentifier("2.5.29.134");
    // System.out.println(spec);
    SignedMessagePayload payload = SignedMessagePayload.newBuilder().setTlsPublicKey(tls_wkp.getPublicKey()).build();
    SignedMessage sm = MsgSigUtil.signMessage(spec, key_pair, payload);
    byte[] sm_data = sm.toByteString().toByteArray();
    cert_builder.addExtension(snow_claim_oid, true, sm_data);
    String algorithm = "SHA256withRSA";
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(tls_wkp.getPrivateKey().toByteArray());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    // ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X509CertificateHolder certificateHolder = cert_builder.build(sigGen);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    return cert;
}
Also used : SignedMessagePayload(snowblossom.proto.SignedMessagePayload) SignedMessage(snowblossom.proto.SignedMessage) ContentSigner(org.bouncycastle.operator.ContentSigner) ByteString(com.google.protobuf.ByteString) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) AddressSpecHash(snowblossom.lib.AddressSpecHash) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 38 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project supply-chain-tools by secure-device-onboard.

the class SimpleCertPathServiceTest method buildCertificate.

X509Certificate buildCertificate(PublicKey signee, PrivateKey signer) throws CertificateException, CertIOException, OperatorCreationException {
    X500Name x500Name = new X500NameBuilder().build();
    JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(x500Name, new BigInteger(Long.toString(System.currentTimeMillis())), Date.from(Instant.now()), Date.from(Instant.now().plusSeconds(1000)), x500Name, signee);
    certificateBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true));
    return new JcaX509CertificateConverter().setProvider(BouncyCastleSingleton.INSTANCE).getCertificate(certificateBuilder.build(new JcaContentSignerBuilder(signatureAlg).build(signer)));
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 39 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project ca3sCore by kuehne-trustable-de.

the class ContentUploadProcessor method buildServerSideKeyAndRequest.

private ResponseEntity<PkcsXXData> buildServerSideKeyAndRequest(UploadPrecheckData uploaded, String requestorName) {
    try {
        Optional<Pipeline> optPipeline = pipelineRepository.findById(uploaded.getPipelineId());
        KeyAlgoLength keyAlgoLength = uploaded.getKeyAlgoLength();
        KeyPair keypair = generateKeyPair(keyAlgoLength);
        NamedValues[] certAttr = uploaded.getCertificateAttributes();
        X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
        List<GeneralName> gnList = new ArrayList<>();
        for (NamedValues nv : certAttr) {
            String name = nv.getName();
            if (nameOIDMap.containsKey(name)) {
                ASN1ObjectIdentifier oid = nameOIDMap.get(name);
                for (String value : nv.getValues()) {
                    if (value != null && !value.isEmpty()) {
                        namebuilder.addRDN(oid, value);
                    }
                }
            } else if ("SAN".equalsIgnoreCase(name)) {
                for (String value : nv.getValues()) {
                    String content = value.trim();
                    if (content.isEmpty()) {
                        continue;
                    }
                    String[] sanParts = content.split(":");
                    if (sanParts.length == 1) {
                        gnList.add(new GeneralName(GeneralName.dNSName, content));
                    } else if (sanParts.length > 1) {
                        if (nameGeneralNameMap.containsKey(sanParts[0].toUpperCase())) {
                            Integer type = nameGeneralNameMap.get(sanParts[0].toUpperCase());
                            gnList.add(new GeneralName(type, sanParts[1]));
                        } else {
                            LOG.warn("SAN certificate attribute has unknown type '{}'", sanParts[0]);
                        }
                    } else {
                        LOG.warn("unexpected SAN info value '{}'", value);
                    }
                }
            } else {
                LOG.warn("certificate attribute '{}' unknown ", name);
            }
        }
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());
        if (!gnList.isEmpty()) {
            GeneralName[] gns = new GeneralName[gnList.size()];
            gnList.toArray(gns);
            GeneralNames subjectAltName = new GeneralNames(gns);
            ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
            extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
            if (optPipeline.isPresent()) {
                Pipeline p = optPipeline.get();
                PipelineView pv = pipelineUtil.from(p);
                if (CsrUsage.TLS_SERVER.equals(pv.getCsrUsage())) {
                    extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
                    extensionsGenerator.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
                } else if (CsrUsage.TLS_CLIENT.equals(pv.getCsrUsage())) {
                    extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
                    extensionsGenerator.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
                } else if (CsrUsage.DOC_SIGNING.equals(pv.getCsrUsage())) {
                    extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation));
                } else if (CsrUsage.CODE_SIGNING.equals(pv.getCsrUsage())) {
                    extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
                    extensionsGenerator.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning));
                } else {
                    LOG.warn("unexpected CsrUsage found '{}'", pv.getCsrUsage());
                }
            }
            p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
        }
        PrivateKey pk = keypair.getPrivate();
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(pk instanceof ECKey ? EC_SIGNATURE_ALG : SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);
        PKCS10CertificationRequest p10CR = p10Builder.build(signer);
        String csrAsPem = CryptoUtil.pkcs10RequestToPem(p10CR);
        LOG.debug("created csr on behalf of user '{}':\n{}", requestorName, csrAsPem);
        Pkcs10RequestHolder p10ReqHolder = cryptoUtil.parseCertificateRequest(p10CR);
        Pkcs10RequestHolderShallow p10ReqHolderShallow = new Pkcs10RequestHolderShallow(p10ReqHolder);
        PkcsXXData p10ReqData = new PkcsXXData(p10ReqHolderShallow);
        CSR csr;
        try {
            csr = startCertificateCreationProcess(csrAsPem, p10ReqData, requestorName, uploaded.getRequestorcomment(), uploaded.getArAttributes(), optPipeline);
        } catch (CAFailureException caFailureException) {
            LOG.info("problem creating certificate", caFailureException);
            String[] messages = ArrayUtils.add(p10ReqData.getWarnings(), caFailureException.getMessage());
            p10ReqData.setWarnings(messages);
            return new ResponseEntity<>(p10ReqData, HttpStatus.OK);
        }
        if (csr != null) {
            csr.setServersideKeyGeneration(true);
            csrRepository.save(csr);
            Instant validTo = Instant.now().plus(30, ChronoUnit.DAYS);
            certUtil.storePrivateKey(csr, keypair, validTo);
            protUtil.createProtectedContent(uploaded.getSecret(), ProtectedContentType.PASSWORD, ContentRelationType.CSR, csr.getId(), -1, validTo);
            Certificate cert = csr.getCertificate();
            if (cert != null) {
                // return the id of the freshly created certificate
                X509CertificateHolder certHolder = cryptoUtil.convertPemToCertificateHolder(cert.getContent());
                p10ReqData = new PkcsXXData(certHolder, cert);
            }
            return new ResponseEntity<>(p10ReqData, HttpStatus.CREATED);
        }
        LOG.warn("problem creating serverside csr object from CSR PEM: \n{}", csrAsPem);
        return new ResponseEntity<>(p10ReqData, HttpStatus.OK);
    } catch (IOException | OperatorCreationException | GeneralSecurityException ex) {
        LOG.warn("problem creating serverside csr: " + ex.getMessage());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ECKey(java.security.interfaces.ECKey) PipelineView(de.trustable.ca3s.core.service.dto.PipelineView) KeyAlgoLength(de.trustable.ca3s.core.service.dto.KeyAlgoLength) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) Instant(java.time.Instant) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) IOException(java.io.IOException) Pkcs10RequestHolder(de.trustable.util.Pkcs10RequestHolder) NamedValues(de.trustable.ca3s.core.service.dto.NamedValues) ResponseEntity(org.springframework.http.ResponseEntity) CAFailureException(de.trustable.ca3s.core.service.exception.CAFailureException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(de.trustable.ca3s.core.domain.Certificate)

Example 40 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project ca3sCore by kuehne-trustable-de.

the class CaCmpConnector method buildCertRequest.

/**
 * @param certReqId
 * @param csr
 * @param hmacSecret
 * @return PKIMessage
 * @throws GeneralSecurityException
 */
public PKIMessage buildCertRequest(long certReqId, final CSR csr, final String hmacSecret) throws GeneralSecurityException {
    // read the pem csr and verify the signature
    PKCS10CertificationRequest p10Req;
    try {
        p10Req = cryptoUtil.parseCertificateRequest(csr.getCsrBase64()).getP10Req();
    } catch (IOException e) {
        LOGGER.error("parsing csr", e);
        throw new GeneralSecurityException(e.getMessage());
    }
    List<RDN> rdnList = new ArrayList<>();
    for (de.trustable.ca3s.core.domain.RDN rdnDao : csr.getRdns()) {
        LOGGER.debug("rdnDao : " + rdnDao.getRdnAttributes());
        List<AttributeTypeAndValue> attrTVList = new ArrayList<AttributeTypeAndValue>();
        if (rdnDao != null && rdnDao.getRdnAttributes() != null) {
            for (RDNAttribute rdnAttr : rdnDao.getRdnAttributes()) {
                ASN1ObjectIdentifier aoi = new ASN1ObjectIdentifier(rdnAttr.getAttributeType());
                ASN1Encodable ae = new DERUTF8String(rdnAttr.getAttributeValue());
                AttributeTypeAndValue attrTV = new AttributeTypeAndValue(aoi, ae);
                attrTVList.add(attrTV);
            }
        }
        RDN rdn = new RDN(attrTVList.toArray(new AttributeTypeAndValue[attrTVList.size()]));
        LOGGER.debug("rdn : " + rdn.size() + " elements");
        rdnList.add(rdn);
    }
    X500Name subjectDN = new X500Name(rdnList.toArray(new RDN[rdnList.size()]));
    LOGGER.debug("subjectDN : " + subjectDN);
    Collection<Extension> certExtList = new ArrayList<>();
    // copy CSR attributes to Extension list
    for (Attribute attribute : p10Req.getAttributes()) {
        for (ASN1Encodable asn1Encodable : attribute.getAttributeValues()) {
            if (asn1Encodable != null) {
                try {
                    Extensions extensions = Extensions.getInstance(asn1Encodable);
                    for (ASN1ObjectIdentifier oid : extensions.getExtensionOIDs()) {
                        LOGGER.debug("copying oid '" + oid.toString() + "' from csr to PKIMessage");
                        certExtList.add(extensions.getExtension(oid));
                    }
                } catch (IllegalArgumentException iae) {
                    LOGGER.debug("processing asn1 value  '" + asn1Encodable + "' caused exception", iae);
                }
            }
        }
    }
    final SubjectPublicKeyInfo keyInfo = p10Req.getSubjectPublicKeyInfo();
    return cryptoUtil.buildCertRequest(certReqId, subjectDN, certExtList, keyInfo, hmacSecret);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) RDNAttribute(de.trustable.ca3s.core.domain.RDNAttribute) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) RDNAttribute(de.trustable.ca3s.core.domain.RDNAttribute) CsrAttribute(de.trustable.ca3s.core.domain.CsrAttribute) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) RDN(org.bouncycastle.asn1.x500.RDN) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)545 IOException (java.io.IOException)161 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)126 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)87 DEROctetString (org.bouncycastle.asn1.DEROctetString)87 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)71 Enumeration (java.util.Enumeration)70 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)70 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)69 ArrayList (java.util.ArrayList)65 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)64 BigInteger (java.math.BigInteger)60 DERSequence (org.bouncycastle.asn1.DERSequence)60 HashSet (java.util.HashSet)57 DERIA5String (org.bouncycastle.asn1.DERIA5String)52 X500Name (org.bouncycastle.asn1.x500.X500Name)52 X509Certificate (java.security.cert.X509Certificate)50 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)47 Extension (org.bouncycastle.asn1.x509.Extension)46