use of org.bouncycastle.asn1.x509.Time in project Openfire by igniterealtime.
the class CertificateManager method createX509V3Certificate.
/**
* Creates an X509 version3 certificate.
*
* @param kp KeyPair that keeps the public and private keys for the new certificate.
* @param days time to live
* @param issuerBuilder IssuerDN builder
* @param subjectBuilder SubjectDN builder
* @param domain Domain of the server.
* @param signAlgoritm Signature algorithm. This can be either a name or an OID.
* @return X509 V3 Certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
PublicKey pubKey = kp.getPublic();
PrivateKey privKey = kp.getPrivate();
byte[] serno = new byte[8];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed((new Date().getTime()));
random.nextBytes(serno);
BigInteger serial = (new java.math.BigInteger(serno)).abs();
X500Name issuerDN = issuerBuilder.build();
X500Name subjectDN = subjectBuilder.build();
// builder
JcaX509v3CertificateBuilder certBuilder = new //
JcaX509v3CertificateBuilder(//
issuerDN, //
serial, //
new Date(), //
new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
subjectDN, //
pubKey);
// add subjectAlternativeName extension
boolean critical = subjectDN.getRDNs().length == 0;
ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
// add keyIdentifiers extensions
JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
try {
// build the certificate
ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
X509CertificateHolder cert = certBuilder.build(signer);
// verify the validity
if (!cert.isValidOn(new Date())) {
throw new GeneralSecurityException("Certificate validity not valid");
}
// verify the signature (self-signed)
ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
if (!cert.isSignatureValid(verifierProvider)) {
throw new GeneralSecurityException("Certificate signature not valid");
}
return new JcaX509CertificateConverter().getCertificate(cert);
} catch (OperatorCreationException | CertException e) {
throw new GeneralSecurityException(e);
}
}
use of org.bouncycastle.asn1.x509.Time in project android_frameworks_base by ResurrectionRemix.
the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.
@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
ASN1ObjectIdentifier sigAlgOid;
AlgorithmIdentifier sigAlgId;
byte[] signature;
switch(mKeymasterAlgorithm) {
case KeymasterDefs.KM_ALGORITHM_EC:
sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
sigAlgId = new AlgorithmIdentifier(sigAlgOid);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(0));
signature = new DERSequence().getEncoded();
break;
case KeymasterDefs.KM_ALGORITHM_RSA:
sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
signature = new byte[1];
break;
default:
throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
}
try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
}
tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
tbsGenerator.setSubject(subject);
tbsGenerator.setIssuer(subject);
tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
tbsGenerator.setSignature(sigAlgId);
TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
ASN1EncodableVector result = new ASN1EncodableVector();
result.add(tbsCertificate);
result.add(sigAlgId);
result.add(new DERBitString(signature));
return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
use of org.bouncycastle.asn1.x509.Time in project android_frameworks_base by AOSPA.
the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.
@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
ASN1ObjectIdentifier sigAlgOid;
AlgorithmIdentifier sigAlgId;
byte[] signature;
switch(mKeymasterAlgorithm) {
case KeymasterDefs.KM_ALGORITHM_EC:
sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
sigAlgId = new AlgorithmIdentifier(sigAlgOid);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(0));
signature = new DERSequence().getEncoded();
break;
case KeymasterDefs.KM_ALGORITHM_RSA:
sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
signature = new byte[1];
break;
default:
throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
}
try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
}
tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
tbsGenerator.setSubject(subject);
tbsGenerator.setIssuer(subject);
tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
tbsGenerator.setSignature(sigAlgId);
TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
ASN1EncodableVector result = new ASN1EncodableVector();
result.add(tbsCertificate);
result.add(sigAlgId);
result.add(new DERBitString(signature));
return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
use of org.bouncycastle.asn1.x509.Time in project oxAuth by GluuFederation.
the class CRLCertificateVerifier method validate.
@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
X509Certificate issuer = issuers.get(0);
ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.CRL, CertificateValidity.UNKNOWN);
try {
Principal subjectX500Principal = certificate.getSubjectX500Principal();
String crlURL = getCrlUri(certificate);
if (crlURL == null) {
log.error("CRL's URL for '" + subjectX500Principal + "' is empty");
return status;
}
log.debug("CRL's URL for '" + subjectX500Principal + "' is '" + crlURL + "'");
X509CRL x509crl = getCrl(crlURL);
if (!validateCRL(x509crl, certificate, issuer, validationDate)) {
log.error("The CRL is not valid!");
status.setValidity(CertificateValidity.INVALID);
return status;
}
X509CRLEntry crlEntry = x509crl.getRevokedCertificate(certificate.getSerialNumber());
if (crlEntry == null) {
log.debug("CRL status is valid for '" + subjectX500Principal + "'");
status.setValidity(CertificateValidity.VALID);
} else if (crlEntry.getRevocationDate().after(validationDate)) {
log.warn("CRL revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate);
status.setRevocationObjectIssuingTime(x509crl.getThisUpdate());
status.setValidity(CertificateValidity.VALID);
} else {
log.info("CRL for certificate '" + subjectX500Principal + "' is revoked since " + crlEntry.getRevocationDate());
status.setRevocationObjectIssuingTime(x509crl.getThisUpdate());
status.setRevocationDate(crlEntry.getRevocationDate());
status.setValidity(CertificateValidity.REVOKED);
}
} catch (Exception ex) {
log.error("CRL exception: ", ex);
}
return status;
}
use of org.bouncycastle.asn1.x509.Time in project poi by apache.
the class XAdESXLSignatureFacet method postSign.
@Override
public void postSign(Document document) throws MarshalException {
LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase");
QualifyingPropertiesDocument qualDoc = null;
QualifyingPropertiesType qualProps = null;
// check for XAdES-BES
NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");
if (qualNl.getLength() == 1) {
try {
qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0), DEFAULT_XML_OPTIONS);
} catch (XmlException e) {
throw new MarshalException(e);
}
qualProps = qualDoc.getQualifyingProperties();
} else {
throw new MarshalException("no XAdES-BES extension present");
}
// create basic XML container structure
UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties();
if (unsignedProps == null) {
unsignedProps = qualProps.addNewUnsignedProperties();
}
UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties();
if (unsignedSigProps == null) {
unsignedSigProps = unsignedProps.addNewUnsignedSignatureProperties();
}
// create the XAdES-T time-stamp
NodeList nlSigVal = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue");
if (nlSigVal.getLength() != 1) {
throw new IllegalArgumentException("SignatureValue is not set.");
}
RevocationData tsaRevocationDataXadesT = new RevocationData();
LOG.log(POILogger.DEBUG, "creating XAdES-T time-stamp");
XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(nlSigVal.item(0)), tsaRevocationDataXadesT);
// marshal the XAdES-T extension
unsignedSigProps.addNewSignatureTimeStamp().set(signatureTimeStamp);
// xadesv141::TimeStampValidationData
if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
insertXChild(unsignedSigProps, validationData);
}
if (signatureConfig.getRevocationDataService() == null) {
/*
* Without revocation data service we cannot construct the XAdES-C
* extension.
*/
return;
}
// XAdES-C: complete certificate refs
CompleteCertificateRefsType completeCertificateRefs = unsignedSigProps.addNewCompleteCertificateRefs();
CertIDListType certIdList = completeCertificateRefs.addNewCertRefs();
/*
* We skip the signing certificate itself according to section
* 4.4.3.2 of the XAdES 1.4.1 specification.
*/
List<X509Certificate> certChain = signatureConfig.getSigningCertificateChain();
int chainSize = certChain.size();
if (chainSize > 1) {
for (X509Certificate cert : certChain.subList(1, chainSize)) {
CertIDType certId = certIdList.addNewCert();
XAdESSignatureFacet.setCertID(certId, signatureConfig, false, cert);
}
}
// XAdES-C: complete revocation refs
CompleteRevocationRefsType completeRevocationRefs = unsignedSigProps.addNewCompleteRevocationRefs();
RevocationData revocationData = signatureConfig.getRevocationDataService().getRevocationData(certChain);
if (revocationData.hasCRLs()) {
CRLRefsType crlRefs = completeRevocationRefs.addNewCRLRefs();
completeRevocationRefs.setCRLRefs(crlRefs);
for (byte[] encodedCrl : revocationData.getCRLs()) {
CRLRefType crlRef = crlRefs.addNewCRLRef();
X509CRL crl;
try {
crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
} catch (CRLException e) {
throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
}
CRLIdentifierType crlIdentifier = crlRef.addNewCRLIdentifier();
String issuerName = crl.getIssuerDN().getName().replace(",", ", ");
crlIdentifier.setIssuer(issuerName);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
cal.setTime(crl.getThisUpdate());
crlIdentifier.setIssueTime(cal);
crlIdentifier.setNumber(getCrlNumber(crl));
DigestAlgAndValueType digestAlgAndValue = crlRef.addNewDigestAlgAndValue();
XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, encodedCrl, signatureConfig.getDigestAlgo());
}
}
if (revocationData.hasOCSPs()) {
OCSPRefsType ocspRefs = completeRevocationRefs.addNewOCSPRefs();
for (byte[] ocsp : revocationData.getOCSPs()) {
try {
OCSPRefType ocspRef = ocspRefs.addNewOCSPRef();
DigestAlgAndValueType digestAlgAndValue = ocspRef.addNewDigestAlgAndValue();
XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, ocsp, signatureConfig.getDigestAlgo());
OCSPIdentifierType ocspIdentifier = ocspRef.addNewOCSPIdentifier();
OCSPResp ocspResp = new OCSPResp(ocsp);
BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResp.getResponseObject();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
cal.setTime(basicOcspResp.getProducedAt());
ocspIdentifier.setProducedAt(cal);
ResponderIDType responderId = ocspIdentifier.addNewResponderID();
RespID respId = basicOcspResp.getResponderId();
ResponderID ocspResponderId = respId.toASN1Primitive();
DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Primitive();
if (2 == derTaggedObject.getTagNo()) {
ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
byte[] key = keyHashOctetString.getOctets();
responderId.setByKey(key);
} else {
X500Name name = X500Name.getInstance(derTaggedObject.getObject());
String nameStr = name.toString();
responderId.setByName(nameStr);
}
} catch (Exception e) {
throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
}
}
}
// marshal XAdES-C
// XAdES-X Type 1 timestamp
List<Node> timeStampNodesXadesX1 = new ArrayList<Node>();
timeStampNodesXadesX1.add(nlSigVal.item(0));
timeStampNodesXadesX1.add(signatureTimeStamp.getDomNode());
timeStampNodesXadesX1.add(completeCertificateRefs.getDomNode());
timeStampNodesXadesX1.add(completeRevocationRefs.getDomNode());
RevocationData tsaRevocationDataXadesX1 = new RevocationData();
LOG.log(POILogger.DEBUG, "creating XAdES-X time-stamp");
XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1);
if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
ValidationDataType timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
insertXChild(unsignedSigProps, timeStampXadesX1ValidationData);
}
// marshal XAdES-X
unsignedSigProps.addNewSigAndRefsTimeStamp().set(timeStampXadesX1);
// XAdES-X-L
CertificateValuesType certificateValues = unsignedSigProps.addNewCertificateValues();
for (X509Certificate certificate : certChain) {
EncapsulatedPKIDataType encapsulatedPKIDataType = certificateValues.addNewEncapsulatedX509Certificate();
try {
encapsulatedPKIDataType.setByteArrayValue(certificate.getEncoded());
} catch (CertificateEncodingException e) {
throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
}
}
RevocationValuesType revocationValues = unsignedSigProps.addNewRevocationValues();
createRevocationValues(revocationValues, revocationData);
// marshal XAdES-X-L
Node n = document.importNode(qualProps.getDomNode(), true);
qualNl.item(0).getParentNode().replaceChild(n, qualNl.item(0));
}
Aggregations