use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project LinLong-Java by zhenwei1108.
the class TSPUtil method validateCertificate.
/**
* Validate the passed in certificate as being of the correct type to be used for time stamping.
* To be valid it must have an ExtendedKeyUsage extension which has a key purpose identifier of
* id-kp-timeStamping.
*
* @param cert the certificate of interest.
* @throws TSPValidationException if the certificate fails on one of the check points.
*/
public static void validateCertificate(X509CertificateHolder cert) throws TSPValidationException {
if (cert.toASN1Structure().getVersionNumber() != 3) {
throw new IllegalArgumentException("Certificate must have an ExtendedKeyUsage extension.");
}
Extension ext = cert.getExtension(Extension.extendedKeyUsage);
if (ext == null) {
throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension.");
}
if (!ext.isCritical()) {
throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");
}
ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(ext.getParsedValue());
if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1) {
throw new TSPValidationException("ExtendedKeyUsage not solely time stamping.");
}
}
use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project athenz by yahoo.
the class Crypto method generateX509Certificate.
public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {
// set validity for the given number of minutes from now
Date notBefore = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(notBefore);
cal.add(Calendar.MINUTE, validityTimeout);
Date notAfter = cal.getTime();
// Generate self-signed certificate
X509Certificate cert;
try {
JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(certReq);
PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();
X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(), publicKey).addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints)).addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// see if we have the dns/rfc822/ip address extensions specified in the csr
ArrayList<GeneralName> altNames = new ArrayList<>();
Attribute[] certAttributes = jcaPKCS10CertificationRequest.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
if (certAttributes != null && certAttributes.length > 0) {
for (Attribute attribute : certAttributes) {
Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
// /CLOVER:OFF
if (gns == null) {
continue;
}
// /CLOVER:ON
GeneralName[] names = gns.getNames();
for (GeneralName name : names) {
switch(name.getTagNo()) {
case GeneralName.dNSName:
case GeneralName.iPAddress:
case GeneralName.rfc822Name:
case GeneralName.uniformResourceIdentifier:
altNames.add(name);
break;
}
}
}
if (!altNames.isEmpty()) {
caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[0])));
}
}
String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER).build(caPrivateKey);
JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
cert = converter.getCertificate(caBuilder.build(caSigner));
// /CLOVER:OFF
} catch (CertificateException ex) {
LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: " + ex.getMessage());
throw new CryptoException(ex);
} catch (OperatorCreationException ex) {
LOG.error("generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: " + ex.getMessage());
throw new CryptoException(ex);
} catch (InvalidKeyException ex) {
LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: " + ex.getMessage());
throw new CryptoException(ex);
} catch (NoSuchAlgorithmException ex) {
LOG.error("generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: " + ex.getMessage());
throw new CryptoException(ex);
} catch (Exception ex) {
LOG.error("generateX509Certificate: unable to generate X509 Certificate: {}", ex.getMessage());
throw new CryptoException("Unable to generate X509 Certificate");
}
// /CLOVER:ON
return cert;
}
use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project nhin-d by DirectProject.
the class PKCS11Commands method createCSR.
@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
final String alias = StringArrayUtil.getRequiredValue(args, 0);
final String commonName = StringArrayUtil.getRequiredValue(args, 1);
final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
// make sure we have a valid keyUsage
if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
System.out.println("Invalid key usage.");
return;
}
final Vector<String> additionalRDNFields = new Vector<String>();
int cnt = 4;
String rdnField;
do {
rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
if (!StringUtils.isEmpty(rdnField))
additionalRDNFields.add(rdnField);
} while (!StringUtils.isEmpty(rdnField));
try {
final KeyStore ks = mgr.getKS();
if (!ks.containsAlias(alias)) {
System.out.println("Entry with key name " + alias + " does not exist.");
return;
}
final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
if (storedCert == null) {
System.out.println("Key name " + alias + " does not contain a certificate that can be exported. This key may not be an RSA key pair.");
return;
}
final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
if (privKey == null) {
System.out.println("Failed to object private key. This key may not be an RSA key pair.");
return;
}
// create the CSR
// create the extensions that we want
final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
// Key Usage
int usage;
if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
usage = KeyUsage.keyEncipherment;
else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
usage = KeyUsage.digitalSignature;
else
usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
// Subject Alt Name
int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
// Extended Key Usage
final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
purposes.add(KeyPurposeId.id_kp_emailProtection);
extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
// Basic constraint
final BasicConstraints bc = new BasicConstraints(false);
extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
// create the extension requests
final X509Extensions exts = extsGen.generate();
final ASN1EncodableVector attributes = new ASN1EncodableVector();
final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
attributes.add(attribute);
final DERSet requestedAttributes = new DERSet(attributes);
// create the DN
final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
final X509Principal xName = new X509Principal(true, subjectPrin.getName());
// create the CSR
final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
final byte[] encodedCSR = request.getEncoded();
final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
final File csrFile = new File(alias + "-CSR.pem");
FileUtils.writeStringToFile(csrFile, csrString);
System.out.println("CSR written to " + csrFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to create CSR : " + e.getMessage());
}
}
use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project nifi by apache.
the class CertificateUtils method generateIssuedCertificate.
/**
* Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
*
* @param dn the distinguished name to use
* @param publicKey the public key to issue the certificate to
* @param extensions extensions extracted from the CSR
* @param issuer the issuer's certificate
* @param issuerKeyPair the issuer's keypair
* @param signingAlgorithm the signing algorithm to use
* @param days the number of days it should be valid for
* @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
* @throws CertificateException if there is an error issuing the certificate
*/
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException {
try {
ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
// Set certificate extensions
// (1) digitalSignature extension
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));
certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
// (2) extendedKeyUsage extension
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// (3) subjectAlternativeName
if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
}
X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
} catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
throw new CertificateException(e);
}
}
use of com.github.zhenwei.core.asn1.x509.ExtendedKeyUsage in project xipki by xipki.
the class CsrGenAction method execute0.
@Override
protected Object execute0() throws Exception {
hashAlgo = hashAlgo.trim().toUpperCase();
if (hashAlgo.indexOf('-') != -1) {
hashAlgo = hashAlgo.replaceAll("-", "");
}
if (needExtensionTypes == null) {
needExtensionTypes = new LinkedList<>();
}
if (wantExtensionTypes == null) {
wantExtensionTypes = new LinkedList<>();
}
// SubjectAltNames
List<Extension> extensions = new LinkedList<>();
ASN1OctetString extnValue = createExtnValueSubjectAltName();
if (extnValue != null) {
ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
extensions.add(new Extension(oid, false, extnValue));
needExtensionTypes.add(oid.getId());
}
// SubjectInfoAccess
extnValue = createExtnValueSubjectInfoAccess();
if (extnValue != null) {
ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
extensions.add(new Extension(oid, false, extnValue));
needExtensionTypes.add(oid.getId());
}
// Keyusage
if (isNotEmpty(keyusages)) {
Set<KeyUsage> usages = new HashSet<>();
for (String usage : keyusages) {
usages.add(KeyUsage.getKeyUsage(usage));
}
org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
ASN1ObjectIdentifier extType = Extension.keyUsage;
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// ExtendedKeyusage
if (isNotEmpty(extkeyusages)) {
ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// QcEuLimitValue
if (isNotEmpty(qcEuLimits)) {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (String m : qcEuLimits) {
StringTokenizer st = new StringTokenizer(m, ":");
try {
String currencyS = st.nextToken();
String amountS = st.nextToken();
String exponentS = st.nextToken();
Iso4217CurrencyCode currency;
try {
int intValue = Integer.parseInt(currencyS);
currency = new Iso4217CurrencyCode(intValue);
} catch (NumberFormatException ex) {
currency = new Iso4217CurrencyCode(currencyS);
}
int amount = Integer.parseInt(amountS);
int exponent = Integer.parseInt(exponentS);
MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue, monterayValue);
vec.add(statment);
} catch (Exception ex) {
throw new Exception("invalid qc-eu-limit '" + m + "'");
}
}
ASN1ObjectIdentifier extType = Extension.qCStatements;
ASN1Sequence extValue = new DERSequence(vec);
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// biometricInfo
if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType) ? new TypeOfBiometricData(Integer.parseInt(biometricType)) : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));
ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
byte[] biometricBytes = IoUtil.read(biometricFile);
MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
md.reset();
byte[] tmpBiometricDataHash = md.digest(biometricBytes);
DERIA5String tmpSourceDataUri = null;
if (biometricUri != null) {
tmpSourceDataUri = new DERIA5String(biometricUri);
}
BiometricData biometricData = new BiometricData(tmpBiometricType, new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash), tmpSourceDataUri);
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(biometricData);
ASN1ObjectIdentifier extType = Extension.biometricInfo;
ASN1Sequence extValue = new DERSequence(vec);
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
} else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
// Do nothing
} else {
throw new Exception("either all of biometric triples (type, hash algo, file)" + " must be set or none of them should be set");
}
for (Extension addExt : getAdditionalExtensions()) {
extensions.add(addExt);
}
needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());
if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes), textToAsn1ObjectIdentifers(wantExtensionTypes));
extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded()));
}
ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain, gm));
Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
if (CollectionUtil.isNonEmpty(extensions)) {
attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions.toArray(new Extension[0])));
}
if (StringUtil.isNotBlank(challengePassword)) {
attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
}
SubjectPublicKeyInfo subjectPublicKeyInfo;
if (signer.getCertificate() != null) {
Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
} else {
subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
}
X500Name subjectDn = getSubject(subject);
PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);
File file = new File(outputFilename);
saveVerbose("saved CSR to file", file, csr.getEncoded());
return null;
}
Aggregations