use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.
the class X509Ca method createGrantedCertTemplate.
private GrantedCertTemplate createGrantedCertTemplate(CertTemplateData certTemplate, RequestorInfo requestor, boolean keyUpdate) throws OperationException {
ParamUtil.requireNonNull("certTemplate", certTemplate);
if (caInfo.getRevocationInfo() != null) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is revoked");
}
IdentifiedX509Certprofile certprofile = getX509Certprofile(certTemplate.getCertprofileName());
if (certprofile == null) {
throw new OperationException(ErrorCode.UNKNOWN_CERT_PROFILE, "unknown cert profile " + certTemplate.getCertprofileName());
}
ConcurrentContentSigner signer = caInfo.getSigner(certprofile.getSignatureAlgorithms());
if (signer == null) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
}
final NameId certprofileIdent = certprofile.getIdent();
if (certprofile.getVersion() != X509CertVersion.v3) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "unknown cert version " + certprofile.getVersion());
}
if (certprofile.isOnlyForRa()) {
if (requestor == null || !requestor.isRa()) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "profile " + certprofileIdent + " not applied to non-RA");
}
}
X500Name requestedSubject = removeEmptyRdns(certTemplate.getSubject());
if (!certprofile.isSerialNumberInReqPermitted()) {
RDN[] rdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_SN);
if (rdns != null && rdns.length > 0) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "subjectDN SerialNumber in request is not permitted");
}
}
Date now = new Date();
Date reqNotBefore;
if (certTemplate.getNotBefore() != null && certTemplate.getNotBefore().after(now)) {
reqNotBefore = certTemplate.getNotBefore();
} else {
reqNotBefore = now;
}
Date grantedNotBefore = certprofile.getNotBefore(reqNotBefore);
// notBefore in the past is not permitted
if (grantedNotBefore.before(now)) {
grantedNotBefore = now;
}
if (certprofile.hasMidnightNotBefore()) {
grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
}
if (grantedNotBefore.before(caInfo.getNotBefore())) {
grantedNotBefore = caInfo.getNotBefore();
if (certprofile.hasMidnightNotBefore()) {
grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
}
}
long time = caInfo.getNoNewCertificateAfter();
if (grantedNotBefore.getTime() > time) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is not permitted to issue certifate after " + new Date(time));
}
SubjectPublicKeyInfo grantedPublicKeyInfo;
try {
grantedPublicKeyInfo = X509Util.toRfc3279Style(certTemplate.getPublicKeyInfo());
} catch (InvalidKeySpecException ex) {
LogUtil.warn(LOG, ex, "invalid SubjectPublicKeyInfo");
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid SubjectPublicKeyInfo");
}
// public key
try {
grantedPublicKeyInfo = certprofile.checkPublicKey(grantedPublicKeyInfo);
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
// CHECK weak public key, like RSA key (ROCA)
if (grantedPublicKeyInfo.getAlgorithm().getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) {
try {
ASN1Sequence seq = ASN1Sequence.getInstance(grantedPublicKeyInfo.getPublicKeyData().getOctets());
if (seq.size() != 2) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
}
BigInteger modulus = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue();
if (RSABrokenKey.isAffected(modulus)) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "RSA public key is too weak");
}
} catch (IllegalArgumentException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
}
}
Date gsmckFirstNotBefore = null;
if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
gsmckFirstNotBefore = grantedNotBefore;
RDN[] cnRdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_CN);
if (cnRdns != null && cnRdns.length > 0) {
String requestedCn = X509Util.rdnValueToString(cnRdns[0].getFirst().getValue());
Long gsmckFirstNotBeforeInSecond = certstore.getNotBeforeOfFirstCertStartsWithCommonName(requestedCn, certprofileIdent);
if (gsmckFirstNotBeforeInSecond != null) {
gsmckFirstNotBefore = new Date(gsmckFirstNotBeforeInSecond * MS_PER_SECOND);
}
// append the commonName with '-' + yyyyMMdd
SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd");
dateF.setTimeZone(new SimpleTimeZone(0, "Z"));
String yyyyMMdd = dateF.format(gsmckFirstNotBefore);
String suffix = "-" + yyyyMMdd;
// append the -yyyyMMdd to the commonName
RDN[] rdns = requestedSubject.getRDNs();
for (int i = 0; i < rdns.length; i++) {
if (ObjectIdentifiers.DN_CN.equals(rdns[i].getFirst().getType())) {
rdns[i] = new RDN(ObjectIdentifiers.DN_CN, new DERUTF8String(requestedCn + suffix));
}
}
requestedSubject = new X500Name(rdns);
}
// end if
}
// end if
// subject
SubjectInfo subjectInfo;
try {
subjectInfo = certprofile.getSubject(requestedSubject);
} catch (CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofileIdent);
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
X500Name grantedSubject = subjectInfo.getGrantedSubject();
// make sure that empty subject is not permitted
ASN1ObjectIdentifier[] attrTypes = grantedSubject.getAttributeTypes();
if (attrTypes == null || attrTypes.length == 0) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "empty subject is not permitted");
}
// make sure that the grantedSubject does not equal the CA's subject
if (X509Util.canonicalizName(grantedSubject).equals(caInfo.getPublicCaInfo().getC14nSubject())) {
throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the same subject as CA is not allowed");
}
boolean duplicateKeyPermitted = caInfo.isDuplicateKeyPermitted();
if (duplicateKeyPermitted && !certprofile.isDuplicateKeyPermitted()) {
duplicateKeyPermitted = false;
}
byte[] subjectPublicKeyData = grantedPublicKeyInfo.getPublicKeyData().getBytes();
long fpPublicKey = FpIdCalculator.hash(subjectPublicKeyData);
if (keyUpdate) {
CertStatus certStatus = certstore.getCertStatusForSubject(caIdent, grantedSubject);
if (certStatus == CertStatus.REVOKED) {
throw new OperationException(ErrorCode.CERT_REVOKED);
} else if (certStatus == CertStatus.UNKNOWN) {
throw new OperationException(ErrorCode.UNKNOWN_CERT);
}
} else {
if (!duplicateKeyPermitted) {
if (certstore.isCertForKeyIssued(caIdent, fpPublicKey)) {
throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key already issued");
}
}
// duplicateSubject check will be processed later
}
// end if(keyUpdate)
StringBuilder msgBuilder = new StringBuilder();
if (subjectInfo.getWarning() != null) {
msgBuilder.append(", ").append(subjectInfo.getWarning());
}
CertValidity validity = certprofile.getValidity();
if (validity == null) {
validity = caInfo.getMaxValidity();
} else if (validity.compareTo(caInfo.getMaxValidity()) > 0) {
validity = caInfo.getMaxValidity();
}
Date maxNotAfter = validity.add(grantedNotBefore);
if (maxNotAfter.getTime() > MAX_CERT_TIME_MS) {
maxNotAfter = new Date(MAX_CERT_TIME_MS);
}
// CHECKSTYLE:SKIP
Date origMaxNotAfter = maxNotAfter;
if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
String str = certprofile.setParameter(SpecialX509CertprofileBehavior.PARAMETER_MAXLIFTIME);
long maxLifetimeInDays = Long.parseLong(str);
Date maxLifetime = new Date(gsmckFirstNotBefore.getTime() + maxLifetimeInDays * DAY_IN_MS - MS_PER_SECOND);
if (maxNotAfter.after(maxLifetime)) {
maxNotAfter = maxLifetime;
}
}
Date grantedNotAfter = certTemplate.getNotAfter();
if (grantedNotAfter != null) {
if (grantedNotAfter.after(maxNotAfter)) {
grantedNotAfter = maxNotAfter;
msgBuilder.append(", notAfter modified");
}
} else {
grantedNotAfter = maxNotAfter;
}
if (grantedNotAfter.after(caInfo.getNotAfter())) {
ValidityMode mode = caInfo.getValidityMode();
if (mode == ValidityMode.CUTOFF) {
grantedNotAfter = caInfo.getNotAfter();
} else if (mode == ValidityMode.STRICT) {
throw new OperationException(ErrorCode.NOT_PERMITTED, "notAfter outside of CA's validity is not permitted");
} else if (mode == ValidityMode.LAX) {
// permitted
} else {
throw new RuntimeException("should not reach here, unknown CA ValidityMode " + mode);
}
// end if (mode)
}
if (certprofile.hasMidnightNotBefore() && !maxNotAfter.equals(origMaxNotAfter)) {
Calendar cal = Calendar.getInstance(certprofile.getTimezone());
cal.setTime(new Date(grantedNotAfter.getTime() - DAY_IN_MS));
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 0);
grantedNotAfter = cal.getTime();
}
String warning = null;
if (msgBuilder.length() > 2) {
warning = msgBuilder.substring(2);
}
GrantedCertTemplate gct = new GrantedCertTemplate(certTemplate.getExtensions(), certprofile, grantedNotBefore, grantedNotAfter, requestedSubject, grantedPublicKeyInfo, fpPublicKey, subjectPublicKeyData, signer, warning);
gct.setGrantedSubject(grantedSubject);
return gct;
}
use of org.bouncycastle.asn1.ocsp.Signature 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 org.bouncycastle.asn1.ocsp.Signature in project spring-cloud-digital-sign by SpringForAll.
the class ServerPKCSUtil method genCsr.
/**
* genCsr
*
* @param alg0 alg
* 密钥算法
* @return
*/
public static String genCsr(String alg0) {
if ("".equals(alg0)) {
alg = alg0;
}
// 产生秘钥对
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 根据秘钥算法配置秘钥长度
if ("SM2".equalsIgnoreCase(alg)) {
kpg.initialize(256);
} else {
kpg.initialize(2048);
}
KeyPair kp = kpg.generateKeyPair();
securityKP = kp;
// 获取公钥以及公钥算法
byte[] publickey = kp.getPublic().getEncoded();
String pubAlg = kp.getPublic().getAlgorithm();
String sAlg = null;
try {
sAlg = AlgorithmId.get(pubAlg).getOID().toString();
} catch (NoSuchAlgorithmException e) {
}
SubjectPublicKeyInfo spki = null;
// 区分SM2和RSA
if (sAlg.equals("1.2.156.10197.1.301")) {
spki = SubjectPublicKeyInfo.getInstance(publickey);
} else {
spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
}
String subject = "CN=defaultName";
X500Name x500 = new X500Name(subject);
// 产生csr构造器
PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
// 构建签名信息
ContentSigner signer = null;
PrivateKey privateKey = kp.getPrivate();
Signature sign = null;
try {
if (privateKey.getAlgorithm().equals("SM2")) {
sign = Signature.getInstance("SM3withSM2");
} else {
sign = Signature.getInstance("SHA1withRSA");
}
sign.initSign(privateKey);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
final Signature sign1 = sign;
signer = new ContentSigner() {
ByteArrayOutputStream originStream = new ByteArrayOutputStream();
public byte[] getSignature() {
try {
sign1.update(originStream.toByteArray());
return sign1.sign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
public OutputStream getOutputStream() {
return originStream;
}
public AlgorithmIdentifier getAlgorithmIdentifier() {
try {
return new AlgorithmIdentifier(AlgorithmId.get(sign1.getAlgorithm()).getOID().toString());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
};
PKCS10CertificationRequestHolder pr = prb.build(signer);
try {
return new String(Base64.encode(pr.getEncoded()));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
use of org.bouncycastle.asn1.ocsp.Signature in project webcert by sklintyg.
the class ASN1UtilImpl method getValue.
@Override
public String getValue(String identifier, InputStream asn1Signature) {
ByteArrayInputStream bais = null;
ASN1InputStream asn1InputStream = null;
try {
bais = convertStream(asn1Signature);
asn1InputStream = new ASN1InputStream(bais);
DERObject obj = asn1InputStream.readObject();
ContentInfo contentInfo = ContentInfo.getInstance(obj);
// Extract certificates
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
return findInCertificate(identifier, (DERObject) signedData.getCertificates().getObjectAt(0));
} catch (IOException e) {
LOG.error("Error parsing signature: {}", e.getMessage());
throw new IllegalStateException(e);
} finally {
IOUtils.closeQuietly(bais);
IOUtils.closeQuietly(asn1InputStream);
}
}
use of org.bouncycastle.asn1.ocsp.Signature in project candlepin by candlepin.
the class X509CRLStreamWriter method write.
/**
* Write a modified CRL to the given output stream. This method will add each entry provided
* via the add() method.
*
* @param out OutputStream to write to
* @throws IOException if something goes wrong
*/
public void write(OutputStream out) throws IOException {
if (!locked || !preScanned) {
throw new IllegalStateException("The instance must be preScanned and locked before writing.");
}
if (emptyCrl) {
/* An empty CRL is going to be missing the revokedCertificates sequence
* and would require a lot of special casing during the streaming process.
* Instead, it is easier to construct the CRL in the normal fashion using
* BouncyCastle. Performance should be acceptable as long as the number of
* CRL entries being added are reasonable in number. Something less than a
* thousand or so should yield adequate performance.
*/
writeToEmptyCrl(out);
return;
}
originalLength = handleHeader(out);
int tag;
int tagNo;
int length;
while (originalLength > count.get()) {
tag = readTag(crlIn, count);
tagNo = readTagNumber(crlIn, tag, count);
length = readLength(crlIn, count);
byte[] entryBytes = new byte[length];
readFullyAndTrack(crlIn, entryBytes, count);
// We only need the serial number and not the rest of the stuff in the entry
ASN1Integer serial = (ASN1Integer) new ASN1InputStream(entryBytes).readObject();
if (deletedEntriesLength == 0 || !deletedEntries.contains(serial.getValue())) {
writeTag(out, tag, tagNo, signer);
writeLength(out, length, signer);
writeValue(out, entryBytes, signer);
}
}
// Write the new entries into the new CRL
for (ASN1Sequence entry : newEntries) {
writeBytes(out, entry.getEncoded(), signer);
}
// Copy the old extensions over
if (newExtensions != null) {
out.write(newExtensions);
signer.getOutputStream().write(newExtensions, 0, newExtensions.length);
}
out.write(signingAlg.getEncoded());
try {
byte[] signature = signer.getSignature();
ASN1BitString signatureBits = new DERBitString(signature);
out.write(signatureBits.getEncoded());
} catch (DataLengthException e) {
throw new IOException("Could not sign", e);
}
}
Aggregations