use of org.bouncycastle.asn1.cms.Attributes in project robovm by robovm.
the class PrivateKeyInfo method toASN1Primitive.
/**
* write out an RSA private key with its associated information
* as described in PKCS8.
* <pre>
* PrivateKeyInfo ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL
* }
* Version ::= INTEGER {v1(0)} (v1,...)
*
* PrivateKey ::= OCTET STRING
*
* Attributes ::= SET OF Attribute
* </pre>
*/
public ASN1Primitive toASN1Primitive() {
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(0));
v.add(algId);
v.add(privKey);
if (attributes != null) {
v.add(new DERTaggedObject(false, 0, attributes));
}
return new DERSequence(v);
}
use of org.bouncycastle.asn1.cms.Attributes in project drill by apache.
the class WebServer method createHttpsConnector.
/**
* Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
* they will be used else a self-signed certificate is generated and used.
*
* @return Initialized {@link ServerConnector} for HTTPS connectios.
* @throws Exception
*/
private ServerConnector createHttpsConnector() throws Exception {
logger.info("Setting up HTTPS connector for web server");
final SslContextFactory sslContextFactory = new SslContextFactory();
if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
logger.info("Using configured SSL settings for web server");
sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));
// TrustStore and TrustStore password are optional
if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
}
}
} else {
logger.info("Using generated self-signed SSL settings for web server");
final SecureRandom random = new SecureRandom();
// Generate a private-public key pair
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, random);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final DateTime now = DateTime.now();
// Create builder for certificate attributes
final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.OU, "Apache Drill (auth-generated)").addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());
final Date notBefore = now.minusMinutes(1).toDate();
final Date notAfter = now.plusYears(5).toDate();
final BigInteger serialNumber = new BigInteger(128, random);
// Create a certificate valid for 5years from now.
final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(// attributes
nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
// Sign the certificate using the private key
final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
// Check the validity
certificate.checkValidity(now.toDate());
// Make sure the certificate is self-signed.
certificate.verify(certificate.getPublicKey());
// Generate a random password for keystore protection
final String keyStorePasswd = RandomStringUtils.random(20);
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate });
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyStorePassword(keyStorePasswd);
}
final HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT));
return sslConnector;
}
use of org.bouncycastle.asn1.cms.Attributes in project drill by axbaretto.
the class WebServer method createHttpsConnector.
/**
* Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
* they will be used else a self-signed certificate is generated and used.
*
* @return Initialized {@link ServerConnector} for HTTPS connections.
* @throws Exception
*/
private ServerConnector createHttpsConnector(int port, int acceptors, int selectors) throws Exception {
logger.info("Setting up HTTPS connector for web server");
final SslContextFactory sslContextFactory = new SslContextFactory();
SSLConfig ssl = new SSLConfigBuilder().config(config).mode(SSLConfig.Mode.SERVER).initializeSSLContext(false).validateKeyStore(true).build();
if (ssl.isSslValid()) {
logger.info("Using configured SSL settings for web server");
sslContextFactory.setKeyStorePath(ssl.getKeyStorePath());
sslContextFactory.setKeyStorePassword(ssl.getKeyStorePassword());
sslContextFactory.setKeyManagerPassword(ssl.getKeyPassword());
if (ssl.hasTrustStorePath()) {
sslContextFactory.setTrustStorePath(ssl.getTrustStorePath());
if (ssl.hasTrustStorePassword()) {
sslContextFactory.setTrustStorePassword(ssl.getTrustStorePassword());
}
}
} else {
logger.info("Using generated self-signed SSL settings for web server");
final SecureRandom random = new SecureRandom();
// Generate a private-public key pair
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, random);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final DateTime now = DateTime.now();
// Create builder for certificate attributes
final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.OU, "Apache Drill (auth-generated)").addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());
final Date notBefore = now.minusMinutes(1).toDate();
final Date notAfter = now.plusYears(5).toDate();
final BigInteger serialNumber = new BigInteger(128, random);
// Create a certificate valid for 5years from now.
final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(// attributes
nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
// Sign the certificate using the private key
final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
// Check the validity
certificate.checkValidity(now.toDate());
// Make sure the certificate is self-signed.
certificate.verify(certificate.getPublicKey());
// Generate a random password for keystore protection
final String keyStorePasswd = RandomStringUtils.random(20);
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate });
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyStorePassword(keyStorePasswd);
}
final HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
final ServerConnector sslConnector = new ServerConnector(embeddedJetty, null, null, null, acceptors, selectors, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(port);
return sslConnector;
}
use of org.bouncycastle.asn1.cms.Attributes 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;
}
use of org.bouncycastle.asn1.cms.Attributes in project xipki by xipki.
the class CsrGenAction method generateRequest.
private PKCS10CertificationRequest generateRequest(ConcurrentContentSigner signer, SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn, Map<ASN1ObjectIdentifier, ASN1Encodable> attributes) throws XiSecurityException {
ParamUtil.requireNonNull("signer", signer);
ParamUtil.requireNonNull("subjectPublicKeyInfo", subjectPublicKeyInfo);
ParamUtil.requireNonNull("subjectDn", subjectDn);
PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo);
if (CollectionUtil.isNonEmpty(attributes)) {
for (ASN1ObjectIdentifier attrType : attributes.keySet()) {
csrBuilder.addAttribute(attrType, attributes.get(attrType));
}
}
ConcurrentBagEntrySigner signer0;
try {
signer0 = signer.borrowSigner();
} catch (NoIdleSignerException ex) {
throw new XiSecurityException(ex.getMessage(), ex);
}
try {
return csrBuilder.build(signer0.value());
} finally {
signer.requiteSigner(signer0);
}
}
Aggregations