use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.
the class IssuerEntry method getIssuerHashAndKeys.
private static Map<HashAlgo, byte[]> getIssuerHashAndKeys(byte[] encodedCert) throws CertificateEncodingException {
byte[] encodedName;
byte[] encodedKey;
try {
Certificate bcCert = Certificate.getInstance(encodedCert);
encodedName = bcCert.getSubject().getEncoded("DER");
encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
} catch (IllegalArgumentException | IOException ex) {
throw new CertificateEncodingException(ex.getMessage(), ex);
}
Map<HashAlgo, byte[]> hashes = new HashMap<>();
for (HashAlgo ha : HashAlgo.values()) {
int hlen = ha.getLength();
byte[] nameAndKeyHash = new byte[(2 + hlen) << 1];
int offset = 0;
nameAndKeyHash[offset++] = 0x04;
nameAndKeyHash[offset++] = (byte) hlen;
System.arraycopy(ha.hash(encodedName), 0, nameAndKeyHash, offset, hlen);
offset += hlen;
nameAndKeyHash[offset++] = 0x04;
nameAndKeyHash[offset++] = (byte) hlen;
System.arraycopy(ha.hash(encodedKey), 0, nameAndKeyHash, offset, hlen);
offset += hlen;
hashes.put(ha, nameAndKeyHash);
}
return hashes;
}
use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.
the class X509SelfSignedCertBuilder method generateSelfSigned.
public static GenerateSelfSignedResult generateSelfSigned(SecurityFactory securityFactory, String signerType, String signerConf, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException, InvalidConfException {
ParamUtil.requireNonNull("securityFactory", securityFactory);
ParamUtil.requireNonBlank("signerType", signerType);
ParamUtil.requireNonNull("certprofile", certprofile);
ParamUtil.requireNonNull("csr", csr);
ParamUtil.requireNonNull("serialNumber", serialNumber);
if (serialNumber.compareTo(BigInteger.ZERO) != 1) {
throw new IllegalArgumentException("serialNumber must not be non-positive: " + serialNumber);
}
X509CertLevel level = certprofile.getCertLevel();
if (X509CertLevel.RootCA != level) {
throw new IllegalArgumentException("certprofile is not of level " + X509CertLevel.RootCA);
}
if (!securityFactory.verifyPopo(csr, null)) {
throw new InvalidConfException("could not validate POP for the CSR");
}
if ("pkcs12".equalsIgnoreCase(signerType) || "jks".equalsIgnoreCase(signerType)) {
ConfPairs keyValues = new ConfPairs(signerConf);
String keystoreConf = keyValues.value("keystore");
if (keystoreConf == null) {
throw new InvalidConfException("required parameter 'keystore' for types PKCS12 and JKS, is not specified");
}
}
ConcurrentContentSigner signer;
try {
List<String[]> signerConfs = CaEntry.splitCaSignerConfs(signerConf);
List<String> restrictedSigAlgos = certprofile.getSignatureAlgorithms();
String thisSignerConf = null;
if (CollectionUtil.isEmpty(restrictedSigAlgos)) {
thisSignerConf = signerConfs.get(0)[1];
} else {
for (String algo : restrictedSigAlgos) {
for (String[] m : signerConfs) {
if (m[0].equals(algo)) {
thisSignerConf = m[1];
break;
}
}
if (thisSignerConf != null) {
break;
}
}
}
if (thisSignerConf == null) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
}
signer = securityFactory.createSigner(signerType, new SignerConf(thisSignerConf), (X509Certificate[]) null);
} catch (XiSecurityException | ObjectCreationException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
SubjectPublicKeyInfo publicKeyInfo;
if (signer.getCertificate() != null) {
// this cert is the dummy one which can be considered only as public key container
Certificate bcCert;
try {
bcCert = Certificate.getInstance(signer.getCertificate().getEncoded());
} catch (Exception ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not reparse certificate: " + ex.getMessage());
}
publicKeyInfo = bcCert.getSubjectPublicKeyInfo();
} else {
PublicKey signerPublicKey = signer.getPublicKey();
try {
publicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signerPublicKey);
} catch (InvalidKeyException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "cannot generate SubjectPublicKeyInfo from publicKey: " + ex.getMessage());
}
}
X509Certificate newCert = generateCertificate(signer, certprofile, csr, serialNumber, publicKeyInfo, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
return new GenerateSelfSignedResult(signerConf, newCert);
}
use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.
the class X509SelfSignedCertBuilder method generateCertificate.
// method generateSelfSigned
private static X509Certificate generateCertificate(ConcurrentContentSigner signer, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, SubjectPublicKeyInfo publicKeyInfo, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException {
SubjectPublicKeyInfo tmpPublicKeyInfo;
try {
tmpPublicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo);
} catch (InvalidKeySpecException ex) {
LOG.warn("SecurityUtil.toRfc3279Style", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
try {
certprofile.checkPublicKey(tmpPublicKeyInfo);
} catch (BadCertTemplateException ex) {
LOG.warn("certprofile.checkPublicKey", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
X500Name requestedSubject = csr.getCertificationRequestInfo().getSubject();
SubjectInfo subjectInfo;
// subject
try {
subjectInfo = certprofile.getSubject(requestedSubject);
} catch (CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofile.getIdent());
} catch (BadCertTemplateException ex) {
LOG.warn("certprofile.getSubject", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
Date notBefore = certprofile.getNotBefore(null);
if (notBefore == null) {
notBefore = new Date();
}
CertValidity validity = certprofile.getValidity();
if (validity == null) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "no validity specified in the profile " + certprofile.getIdent());
}
Date notAfter = validity.add(notBefore);
X500Name grantedSubject = subjectInfo.getGrantedSubject();
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(grantedSubject, serialNumber, notBefore, notAfter, grantedSubject, tmpPublicKeyInfo);
PublicCaInfo publicCaInfo = new PublicCaInfo(grantedSubject, serialNumber, null, null, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
Extensions extensions = null;
ASN1Set attrs = csr.getCertificationRequestInfo().getAttributes();
for (int i = 0; i < attrs.size(); i++) {
Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
}
}
try {
addExtensions(certBuilder, certprofile, requestedSubject, grantedSubject, extensions, tmpPublicKeyInfo, publicCaInfo, notBefore, notAfter);
ConcurrentBagEntrySigner signer0 = signer.borrowSigner();
X509CertificateHolder certHolder;
try {
certHolder = certBuilder.build(signer0.value());
} finally {
signer.requiteSigner(signer0);
}
Certificate bcCert = certHolder.toASN1Structure();
return X509Util.parseCert(bcCert.getEncoded());
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
} catch (NoIdleSignerException | CertificateException | IOException | CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
}
use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.
the class X509Ca method generateCertificate0.
private X509CertificateInfo generateCertificate0(GrantedCertTemplate gct, RequestorInfo requestor, boolean keyUpdate, RequestType reqType, byte[] transactionId, AuditEvent event) throws OperationException {
ParamUtil.requireNonNull("gct", gct);
event.addEventData(CaAuditConstants.NAME_reqSubject, X509Util.getRfc4519Name(gct.requestedSubject));
event.addEventData(CaAuditConstants.NAME_certprofile, gct.certprofile.getIdent().getName());
event.addEventData(CaAuditConstants.NAME_notBefore, DateUtil.toUtcTimeyyyyMMddhhmmss(gct.grantedNotBefore));
event.addEventData(CaAuditConstants.NAME_notAfter, DateUtil.toUtcTimeyyyyMMddhhmmss(gct.grantedNotAfter));
adaptGrantedSubejct(gct);
IdentifiedX509Certprofile certprofile = gct.certprofile;
boolean publicKeyCertInProcessExisted = publicKeyCertsInProcess.add(gct.fpPublicKey);
if (!publicKeyCertInProcessExisted) {
if (!certprofile.isDuplicateKeyPermitted()) {
throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the given public key already in process");
}
}
if (!subjectCertsInProcess.add(gct.fpSubject)) {
if (!certprofile.isDuplicateSubjectPermitted()) {
if (!publicKeyCertInProcessExisted) {
publicKeyCertsInProcess.remove(gct.fpPublicKey);
}
throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the given subject " + gct.grantedSubjectText + " already in process");
}
}
try {
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caInfo.getPublicCaInfo().getX500Subject(), caInfo.nextSerial(), gct.grantedNotBefore, gct.grantedNotAfter, gct.grantedSubject, gct.grantedPublicKey);
X509CertificateInfo ret;
try {
X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
X509Certificate crlSignerCert = (crlSigner == null) ? null : crlSigner.getCert();
ExtensionValues extensionTuples = certprofile.getExtensions(gct.requestedSubject, gct.grantedSubject, gct.extensions, gct.grantedPublicKey, caInfo.getPublicCaInfo(), crlSignerCert, gct.grantedNotBefore, gct.grantedNotAfter);
if (extensionTuples != null) {
for (ASN1ObjectIdentifier extensionType : extensionTuples.getExtensionTypes()) {
ExtensionValue extValue = extensionTuples.getExtensionValue(extensionType);
certBuilder.addExtension(extensionType, extValue.isCritical(), extValue.getValue());
}
}
ConcurrentBagEntrySigner signer0;
try {
signer0 = gct.signer.borrowSigner();
} catch (NoIdleSignerException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
X509CertificateHolder certHolder;
try {
certHolder = certBuilder.build(signer0.value());
} finally {
gct.signer.requiteSigner(signer0);
}
Certificate bcCert = certHolder.toASN1Structure();
byte[] encodedCert = bcCert.getEncoded();
int maxCertSize = gct.certprofile.getMaxCertSize();
if (maxCertSize > 0) {
int certSize = encodedCert.length;
if (certSize > maxCertSize) {
throw new OperationException(ErrorCode.NOT_PERMITTED, String.format("certificate exceeds the maximal allowed size: %d > %d", certSize, maxCertSize));
}
}
X509Certificate cert;
try {
cert = X509Util.toX509Cert(bcCert);
} catch (CertificateException ex) {
String message = "should not happen, could not parse generated certificate";
LOG.error(message, ex);
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
if (!verifySignature(cert)) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not verify the signature of generated certificate");
}
X509CertWithDbId certWithMeta = new X509CertWithDbId(cert, encodedCert);
ret = new X509CertificateInfo(certWithMeta, caIdent, caCert, gct.grantedPublicKeyData, gct.certprofile.getIdent(), requestor.getIdent());
if (requestor instanceof ByUserRequestorInfo) {
ret.setUser((((ByUserRequestorInfo) requestor).getUserId()));
}
ret.setReqType(reqType);
ret.setTransactionId(transactionId);
ret.setRequestedSubject(gct.requestedSubject);
if (publishCertificate0(ret) == 1) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not save certificate");
}
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
} catch (OperationException ex) {
throw ex;
} catch (Throwable th) {
LogUtil.error(LOG, th, "could not generate certificate");
throw new OperationException(ErrorCode.SYSTEM_FAILURE, th);
}
if (gct.warning != null) {
ret.setWarningMessage(gct.warning);
}
return ret;
} finally {
publicKeyCertsInProcess.remove(gct.fpPublicKey);
subjectCertsInProcess.remove(gct.fpSubject);
}
}
use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.
the class ScepUtil method generateSelfsignedCert.
public static X509Certificate generateSelfsignedCert(X500Name subjectDn, SubjectPublicKeyInfo pubKeyInfo, PrivateKey identityKey) throws CertificateException {
requireNonNull("subjectDn", subjectDn);
requireNonNull("pubKeyInfo", pubKeyInfo);
requireNonNull("identityKey", identityKey);
Date notBefore = new Date(System.currentTimeMillis() - 5 * MIN_IN_MS);
Date notAfter = new Date(notBefore.getTime() + 30 * DAY_IN_MS);
X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.ONE, notBefore, notAfter, subjectDn, pubKeyInfo);
X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.dataEncipherment | X509KeyUsage.keyAgreement | X509KeyUsage.keyEncipherment);
try {
certGenerator.addExtension(Extension.keyUsage, true, ku);
} catch (CertIOException ex) {
throw new CertificateException("could not generate self-signed certificate: " + ex.getMessage(), ex);
}
String sigAlgorithm = ScepUtil.getSignatureAlgorithm(identityKey, ScepHashAlgo.SHA1);
ContentSigner contentSigner;
try {
contentSigner = new JcaContentSignerBuilder(sigAlgorithm).build(identityKey);
} catch (OperatorCreationException ex) {
throw new CertificateException("error while creating signer", ex);
}
Certificate asn1Cert = certGenerator.build(contentSigner).toASN1Structure();
return toX509Cert(asn1Cert);
}
Aggregations