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());
}
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;
}
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)));
}
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);
}
}
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);
}
Aggregations