use of com.github.zhenwei.core.asn1.x509.KeyUsage in project ozone by apache.
the class DefaultProfile method validateKeyUsage.
/**
* This function validates that the KeyUsage Bits are subset of the Bits
* permitted by the ozone profile.
*
* @param ext - KeyUsage Extension.
* @param profile - PKI Profile - In this case this profile.
* @return True, if the request key usage is a subset, false otherwise.
*/
private static Boolean validateKeyUsage(Extension ext, PKIProfile profile) {
KeyUsage keyUsage = profile.getKeyUsage();
KeyUsage requestedUsage = KeyUsage.getInstance(ext.getParsedValue());
BitSet profileBitSet = BitSet.valueOf(keyUsage.getBytes());
BitSet requestBitSet = BitSet.valueOf(requestedUsage.getBytes());
// Check if the requestBitSet is a subset of profileBitSet
// p & r == r should be equal if it is a subset.
profileBitSet.and(requestBitSet);
return profileBitSet.equals(requestBitSet);
}
use of com.github.zhenwei.core.asn1.x509.KeyUsage in project qpid-broker-j by apache.
the class TlsResourceBuilder method generateIntermediateCertificate.
private static X509Certificate generateIntermediateCertificate(final KeyPair keyPair, final KeyCertificatePair rootCA, final String dn, final ValidityPeriod validityPeriod, final String crlUri) throws CertificateException {
try {
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(rootCA.getCertificate(), generateSerialNumber(), new Date(validityPeriod.getFrom().toEpochMilli()), new Date(validityPeriod.getTo().toEpochMilli()), new X500Name(RFC4519Style.INSTANCE, dn), keyPair.getPublic());
// builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
builder.addExtension(createAuthorityKeyExtension(rootCA.getCertificate().getPublicKey()));
if (crlUri != null) {
builder.addExtension(createDistributionPointExtension(crlUri));
}
return buildX509Certificate(builder, rootCA.getPrivateKey());
} catch (OperatorException | IOException e) {
throw new CertificateException(e);
}
}
use of com.github.zhenwei.core.asn1.x509.KeyUsage in project helios by spotify.
the class X509CertificateFactory method generate.
private CertificateAndPrivateKey generate(final AgentProxy agentProxy, final Identity identity, final String username) {
final UUID uuid = new UUID();
final Calendar calendar = Calendar.getInstance();
final X500Name issuerdn = new X500Name("C=US,O=Spotify,CN=helios-client");
final X500Name subjectdn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();
calendar.add(Calendar.MILLISECOND, -validBeforeMilliseconds);
final Date notBefore = calendar.getTime();
calendar.add(Calendar.MILLISECOND, validBeforeMilliseconds + validAfterMilliseconds);
final Date notAfter = calendar.getTime();
// Reuse the UUID time as a SN
final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();
try {
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerdn, serialNumber, notBefore, notAfter, subjectdn, subjectPublicKeyInfo);
final DigestCalculator digestCalculator = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);
final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
log.info("generating an X509 certificate for {} with key ID={} and identity={}", username, keyIdHex, identity.getComment());
builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
final X509CertificateHolder holder = builder.build(new SshAgentContentSigner(agentProxy, identity));
final X509Certificate certificate = CERTIFICATE_CONVERTER.getCertificate(holder);
log.debug("generated certificate:\n{}", asPemString(certificate));
return new CertificateAndPrivateKey(certificate, keyPair.getPrivate());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
use of com.github.zhenwei.core.asn1.x509.KeyUsage 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.KeyUsage in project nhin-d by DirectProject.
the class CertGenerator method createLeafCertificate.
private static CertCreateFields createLeafCertificate(CertCreateFields fields, KeyPair keyPair, boolean addAltNames) throws Exception {
String altName = "";
StringBuilder dnBuilder = new StringBuilder();
// create the DN
if (fields.getAttributes().containsKey("EMAILADDRESS")) {
dnBuilder.append("EMAILADDRESS=").append(fields.getAttributes().get("EMAILADDRESS")).append(", ");
altName = fields.getAttributes().get("EMAILADDRESS").toString();
}
if (fields.getAttributes().containsKey("CN"))
dnBuilder.append("CN=").append(fields.getAttributes().get("CN")).append(", ");
if (fields.getAttributes().containsKey("C"))
dnBuilder.append("C=").append(fields.getAttributes().get("C")).append(", ");
if (fields.getAttributes().containsKey("ST"))
dnBuilder.append("ST=").append(fields.getAttributes().get("ST")).append(", ");
if (fields.getAttributes().containsKey("L"))
dnBuilder.append("L=").append(fields.getAttributes().get("L")).append(", ");
if (fields.getAttributes().containsKey("O"))
dnBuilder.append("O=").append(fields.getAttributes().get("O")).append(", ");
String DN = dnBuilder.toString().trim();
if (DN.endsWith(","))
DN = DN.substring(0, DN.length() - 1);
X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.DAY_OF_MONTH, fields.getExpDays());
// not the best way to do this... generally done with a db file
v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
// issuer is the parent cert
v1CertGen.setIssuerDN(fields.getSignerCert().getSubjectX500Principal());
v1CertGen.setNotBefore(start.getTime());
v1CertGen.setNotAfter(end.getTime());
v1CertGen.setSubjectDN(new X509Principal(DN));
v1CertGen.setPublicKey(keyPair.getPublic());
v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
// pointer to the parent CA
v1CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(fields.getSignerCert()));
v1CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
boolean allowToSign = (fields.getAttributes().get("ALLOWTOSIGN") != null && fields.getAttributes().get("ALLOWTOSIGN").toString().equalsIgnoreCase("true"));
v1CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(allowToSign));
int keyUsage = 0;
if (fields.getAttributes().get("KEYENC") != null && fields.getAttributes().get("KEYENC").toString().equalsIgnoreCase("true"))
keyUsage = keyUsage | KeyUsage.keyEncipherment;
if (fields.getAttributes().get("DIGSIG") != null && fields.getAttributes().get("DIGSIG").toString().equalsIgnoreCase("true"))
keyUsage = keyUsage | KeyUsage.digitalSignature;
if (keyUsage > 0)
v1CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(keyUsage));
if (fields.getSignerCert().getSubjectAlternativeNames() != null) {
for (List<?> names : fields.getSignerCert().getSubjectAlternativeNames()) {
GeneralNames issuerAltName = new GeneralNames(new GeneralName((Integer) names.get(0), names.get(1).toString()));
v1CertGen.addExtension(X509Extensions.IssuerAlternativeName, false, issuerAltName);
}
}
if (addAltNames && !altName.isEmpty()) {
int nameType = altName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
GeneralNames subjectAltName = new GeneralNames(new GeneralName(nameType, altName));
v1CertGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
}
// use the CA's private key to sign the certificate
X509Certificate newCACert = v1CertGen.generate((PrivateKey) fields.getSignerKey(), CryptoExtensions.getJCEProviderName());
// validate the certificate
newCACert.verify(fields.getSignerCert().getPublicKey());
// write the certificate the file system
writeCertAndKey(newCACert, keyPair.getPrivate(), fields);
return fields;
}
Aggregations