use of org.spongycastle.asn1.x509.BasicConstraints in project vespa by vespa-engine.
the class X509CertificateBuilder method build.
public X509Certificate build() {
try {
JcaX509v3CertificateBuilder jcaCertBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(serialNumber), Date.from(notBefore), Date.from(notAfter), subject, certPublicKey);
if (basicConstraintsExtension != null) {
jcaCertBuilder.addExtension(Extension.basicConstraints, basicConstraintsExtension.isCritical, new BasicConstraints(basicConstraintsExtension.isCertAuthorityCertificate));
}
if (!subjectAlternativeNames.isEmpty()) {
GeneralNames generalNames = new GeneralNames(subjectAlternativeNames.stream().map(san -> new GeneralName(GeneralName.dNSName, san)).toArray(GeneralName[]::new));
jcaCertBuilder.addExtension(Extension.subjectAlternativeName, false, generalNames);
}
ContentSigner contentSigner = new JcaContentSignerBuilder(signingAlgorithm.getAlgorithmName()).setProvider(BouncyCastleProviderHolder.getInstance()).build(caPrivateKey);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProviderHolder.getInstance()).getCertificate(jcaCertBuilder.build(contentSigner));
} catch (OperatorException | GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
use of org.spongycastle.asn1.x509.BasicConstraints in project jruby-openssl by jruby.
the class X509Extension method value.
@JRubyMethod
public RubyString value(final ThreadContext context) {
if (this.value instanceof RubyString) {
// return the same as set
return (RubyString) this.value;
}
final Ruby runtime = context.runtime;
final String oid = getRealObjectID().getId();
try {
if (oid.equals("2.5.29.19")) {
// basicConstraints
ASN1Sequence seq2 = (ASN1Sequence) ASN1.readObject(getRealValueEncoded());
final ByteList val = new ByteList(32);
if (seq2.size() > 0) {
val.append(CA_);
ASN1Encodable obj0 = seq2.getObjectAt(0);
final boolean bool;
if (obj0 instanceof ASN1Boolean) {
bool = ((ASN1Boolean) obj0).isTrue();
} else {
// NOTE: keep it due BC <= 1.50
bool = ((DERBoolean) obj0).isTrue();
}
val.append(bool ? TRUE : FALSE);
}
if (seq2.size() > 1) {
val.append(", pathlen:".getBytes());
val.append(seq2.getObjectAt(1).toString().getBytes());
}
return runtime.newString(val);
}
if (oid.equals("2.5.29.15")) {
// keyUsage
final byte[] enc = getRealValueEncoded();
byte b3 = 0;
byte b2 = enc[2];
if (enc.length > 3)
b3 = enc[3];
final ByteList val = new ByteList(64);
byte[] sep = _;
if ((b2 & (byte) 128) != 0) {
val.append(sep);
val.append(Decipher_Only);
sep = SEP;
}
if ((b3 & (byte) 128) != 0) {
val.append(sep);
val.append(Digital_Signature);
sep = SEP;
}
if ((b3 & (byte) 64) != 0) {
val.append(sep);
val.append(Non_Repudiation);
sep = SEP;
}
if ((b3 & (byte) 32) != 0) {
val.append(sep);
val.append(Key_Encipherment);
sep = SEP;
}
if ((b3 & (byte) 16) != 0) {
val.append(sep);
val.append(Data_Encipherment);
sep = SEP;
}
if ((b3 & (byte) 8) != 0) {
val.append(sep);
val.append(Key_Agreement);
sep = SEP;
}
if ((b3 & (byte) 4) != 0) {
val.append(sep);
val.append(Certificate_Sign);
sep = SEP;
}
if ((b3 & (byte) 2) != 0) {
val.append(sep);
val.append(CRL_Sign);
sep = SEP;
}
if ((b3 & (byte) 1) != 0) {
// sep = SEP;
val.append(sep);
// sep = SEP;
val.append(Encipher_Only);
}
return runtime.newString(val);
}
if (oid.equals("2.16.840.1.113730.1.1")) {
// nsCertType
final byte b0 = getRealValueEncoded()[0];
final ByteList val = new ByteList(64);
byte[] sep = _;
if ((b0 & (byte) 128) != 0) {
val.append(sep);
val.append(SSL_Client);
sep = SEP;
}
if ((b0 & (byte) 64) != 0) {
val.append(sep);
val.append(SSL_Server);
sep = SEP;
}
if ((b0 & (byte) 32) != 0) {
val.append(sep);
val.append(SMIME);
sep = SEP;
}
if ((b0 & (byte) 16) != 0) {
val.append(sep);
val.append(Object_Signing);
sep = SEP;
}
if ((b0 & (byte) 8) != 0) {
val.append(sep);
val.append(Unused);
sep = SEP;
}
if ((b0 & (byte) 4) != 0) {
val.append(sep);
val.append(SSL_CA);
sep = SEP;
}
if ((b0 & (byte) 2) != 0) {
val.append(sep);
val.append(SMIME_CA);
sep = SEP;
}
if ((b0 & (byte) 1) != 0) {
val.append(sep);
val.append(Object_Signing_CA);
}
return runtime.newString(val);
}
if (oid.equals("2.5.29.14")) {
// subjectKeyIdentifier
ASN1Encodable value = getRealValue();
if (value instanceof ASN1OctetString) {
byte[] octets = ((ASN1OctetString) value).getOctets();
if (octets.length > 0 && octets[0] == BERTags.OCTET_STRING) {
// read nested octets
value = ASN1.readObject(octets);
}
}
return runtime.newString(hexBytes(keyidBytes(value.toASN1Primitive()), 0));
}
if (oid.equals("2.5.29.35")) {
// authorityKeyIdentifier
ASN1Encodable value = getRealValue();
if (value instanceof ASN1OctetString) {
value = ASN1.readObject(((ASN1OctetString) value).getOctets());
}
final ByteList val = new ByteList(72);
val.append(keyid_);
if (value instanceof ASN1Sequence) {
final ASN1Sequence seq = (ASN1Sequence) value;
final int size = seq.size();
if (size == 0)
return RubyString.newEmptyString(runtime);
ASN1Primitive keyid = seq.getObjectAt(0).toASN1Primitive();
hexBytes(keyidBytes(keyid), val).append('\n');
for (int i = 1; i < size; i++) {
final ASN1Encodable issuer = seq.getObjectAt(i);
// NOTE: blindly got OpenSSL tests passing (likely in-complete) :
if (issuer instanceof ASN1TaggedObject) {
ASN1Primitive obj = ((ASN1TaggedObject) issuer).getObject();
switch(((ASN1TaggedObject) issuer).getTagNo()) {
case 1:
if (obj instanceof ASN1TaggedObject) {
formatGeneralName(GeneralName.getInstance(obj), val, true);
}
break;
case // serial
2:
val.append(new byte[] { 's', 'e', 'r', 'i', 'a', 'l', ':' });
if (obj instanceof ASN1Integer) {
hexBytes(((ASN1Integer) obj).getValue().toByteArray(), val);
} else {
hexBytes(((ASN1OctetString) obj).getOctets(), val);
}
break;
}
}
val.append('\n');
}
return runtime.newString(val);
}
hexBytes(keyidBytes(value.toASN1Primitive()), val).append('\n');
return runtime.newString(val);
}
if (oid.equals("2.5.29.21")) {
// CRLReason
final IRubyObject value = getValue(runtime);
switch(RubyNumeric.fix2int(value)) {
case 0:
return runtime.newString(new ByteList(Unspecified));
case 1:
return RubyString.newString(runtime, "Key Compromise");
case 2:
return RubyString.newString(runtime, "CA Compromise");
case 3:
return RubyString.newString(runtime, "Affiliation Changed");
case 4:
return RubyString.newString(runtime, "Superseded");
case 5:
return RubyString.newString(runtime, "Cessation Of Operation");
case 6:
return RubyString.newString(runtime, "Certificate Hold");
case 8:
return RubyString.newString(runtime, "Remove From CRL");
case 9:
return RubyString.newString(runtime, "Privilege Withdrawn");
default:
return runtime.newString(new ByteList(Unspecified));
}
}
if (oid.equals("2.5.29.17") || oid.equals("2.5.29.18")) {
// subjectAltName || issuerAltName
try {
ASN1Encodable value = getRealValue();
final ByteList val = new ByteList(64);
if (value instanceof ASN1TaggedObject) {
formatGeneralName(GeneralName.getInstance(value), val, false);
return runtime.newString(val);
}
if (value instanceof GeneralName) {
formatGeneralName((GeneralName) value, val, false);
return runtime.newString(val);
}
if (value instanceof ASN1OctetString) {
// decoded octets will end up as an ASN1Sequence instance :
value = ASN1.readObject(((ASN1OctetString) value).getOctets());
}
if (value instanceof ASN1TaggedObject) {
// DERTaggedObject (issuerAltName wrapping)
formatGeneralName(GeneralName.getInstance(value), val, false);
return runtime.newString(val);
}
final GeneralName[] names = GeneralNames.getInstance(value).getNames();
for (int i = 0; i < names.length; i++) {
boolean other = formatGeneralName(names[i], val, false);
if (i < names.length - 1) {
if (other)
val.append(';');
else
val.append(',').append(' ');
}
}
return runtime.newString(val);
} catch (IllegalArgumentException e) {
debugStackTrace(runtime, e);
return rawValueAsString(context);
}
}
if (oid.equals("2.5.29.37")) {
// extendedKeyUsage
final ByteList val = new ByteList(64);
if (this.value instanceof ASN1Sequence) {
// opt "short" path
final ASN1Sequence seq = (ASN1Sequence) this.value;
final int size = seq.size();
for (int i = 0; i < size; i++) {
ASN1Encodable o = seq.getObjectAt(i);
String name = o.toString();
Integer nid = ASN1.oid2nid(runtime, new ASN1ObjectIdentifier(name));
if (nid != null)
name = ASN1.nid2ln(runtime, nid);
if (name == null)
name = o.toString();
val.append(ByteList.plain(name));
if (i < size - 1)
val.append(',').append(' ');
}
return runtime.newString(val);
}
final IRubyObject value = getValue(runtime);
if (value instanceof RubyArray) {
final RubyArray arr = (RubyArray) value;
final int size = arr.size();
for (int i = 0; i < size; i++) {
IRubyObject entry = arr.eltInternal(i);
if ("ObjectId".equals(entry.getMetaClass().getBaseName())) {
entry = entry.callMethod(context, "ln");
} else if (entry.respondsTo("value")) {
entry = entry.callMethod(context, "value");
}
val.append(entry.asString().getByteList());
if (i < size - 1)
val.append(',').append(' ');
}
}
return runtime.newString(val);
}
return rawValueAsString(context);
} catch (IOException e) {
debugStackTrace(runtime, e);
throw newExtensionError(runtime, e);
}
}
use of org.spongycastle.asn1.x509.BasicConstraints in project Openfire by igniterealtime.
the class KeystoreTestUtils method generateTestCertificate.
private static X509Certificate generateTestCertificate(final boolean isValid, final KeyPair issuerKeyPair, final KeyPair subjectKeyPair, int indexAwayFromEndEntity) throws Exception {
// Issuer and Subject.
final X500Name subject = new X500Name("CN=" + Base64.encodeBytes(subjectKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
final X500Name issuer = new X500Name("CN=" + Base64.encodeBytes(issuerKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
// Validity
final Date notBefore;
final Date notAfter;
if (isValid) {
// 30 days ago
notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30));
// 99 days from now.
notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99));
} else {
// Generate a certificate for which the validate period has expired.
// 40 days ago
notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 40));
// 10 days ago
notAfter = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 10));
}
// The new certificate should get a unique serial number.
final BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, subjectKeyPair.getPublic());
// When this certificate is used to sign another certificate, basic constraints need to be set.
if (indexAwayFromEndEntity > 0) {
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(indexAwayFromEndEntity - 1));
}
final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(issuerKeyPair.getPrivate());
final X509CertificateHolder certificateHolder = builder.build(contentSigner);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
}
use of org.spongycastle.asn1.x509.BasicConstraints in project robovm by robovm.
the class CertificateFactoryTest method generateCertificate.
@SuppressWarnings("deprecation")
private static KeyHolder generateCertificate(boolean isCa, KeyHolder issuer) throws Exception {
Date startDate = new Date();
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
// Jan 1, 2100 UTC
cal.set(2100, 0, 1, 0, 0, 0);
Date expiryDate = cal.getTime();
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = kpg.generateKeyPair();
BigInteger serial;
X500Principal issuerPrincipal;
X500Principal subjectPrincipal;
PrivateKey caKey;
if (issuer != null) {
serial = issuer.certificate.getSerialNumber().add(BigInteger.ONE);
subjectPrincipal = new X500Principal("CN=Test Certificate Serial #" + serial.toString());
issuerPrincipal = issuer.certificate.getSubjectX500Principal();
caKey = issuer.privateKey;
} else {
serial = BigInteger.ONE;
subjectPrincipal = new X500Principal("CN=Test CA, O=Tests, C=US");
issuerPrincipal = subjectPrincipal;
caKey = keyPair.getPrivate();
}
BasicConstraints basicConstraints;
if (isCa) {
basicConstraints = new BasicConstraints(10 - serial.intValue());
} else {
basicConstraints = new BasicConstraints(false);
}
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(serial);
certGen.setIssuerDN(issuerPrincipal);
certGen.setNotBefore(startDate);
certGen.setNotAfter(expiryDate);
certGen.setSubjectDN(subjectPrincipal);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA1withRSA");
if (issuer != null) {
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuer.certificate));
} else {
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
}
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
certGen.addExtension(X509Extensions.BasicConstraints, true, basicConstraints);
X509Certificate cert = certGen.generate(caKey);
KeyHolder holder = new KeyHolder();
holder.certificate = cert;
holder.privateKey = keyPair.getPrivate();
return holder;
}
use of org.spongycastle.asn1.x509.BasicConstraints 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);
}
}
Aggregations