List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName
public GeneralName(int tag, String name)
From source file:com.yahoo.athenz.auth.util.CryptoTest.java
License:Apache License
@Test(dataProvider = "x500Principal") public void testX509CSRrequestWithPrivateKeyOnly(String x500Principal, boolean badRequest) throws Exception { PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey); String certRequest = null;//from w ww . j a v a 2 s. c om GeneralName otherName1 = new GeneralName(GeneralName.otherName, new DERIA5String("role1")); GeneralName otherName2 = new GeneralName(GeneralName.otherName, new DERIA5String("role2")); GeneralName[] sanArray = new GeneralName[] { otherName1, otherName2 }; try { certRequest = Crypto.generateX509CSR(privateKey, x500Principal, sanArray); } catch (Exception e) { if (!badRequest) { fail("Should not have failed to create csr"); } } if (!badRequest) { //Now validate the csr Crypto.getPKCS10CertRequest(certRequest); } }
From source file:com.yahoo.athenz.example.instance.InstanceClientRefresh.java
License:Apache License
public static String generateCSR(String domainName, String serviceName, String instanceId, String dnsSuffix, PrivateKey key) {//from w w w.java2s . co m final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz"; // now let's generate our dsnName field based on our principal's details StringBuilder dnsName = new StringBuilder(128); dnsName.append(serviceName); dnsName.append('.'); dnsName.append(domainName.replace('.', '-')); dnsName.append('.'); dnsName.append(dnsSuffix); GeneralName[] sanArray = new GeneralName[2]; sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString())); // next we include our instance id StringBuilder dnsInstance = new StringBuilder(128); dnsInstance.append(instanceId); dnsInstance.append(".instanceid.athenz."); dnsInstance.append(dnsSuffix); sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString())); String csr = null; try { csr = Crypto.generateX509CSR(key, dn, sanArray); } catch (OperatorCreationException | IOException ex) { System.err.println(ex.getMessage()); } return csr; }
From source file:com.yahoo.athenz.zts.ZTSClient.java
License:Apache License
/** * Generate a Role Certificate request that could be sent to ZTS * to obtain a X509 Certificate for the requested role. * @param principalDomain name of the principal's domain * @param principalService name of the principal's service * @param roleDomainName name of the domain where role is defined * @param roleName name of the role to get a certificate request for * @param privateKey private key for the service identity for the caller * @param csrDn string identifying the dn for the csr without the cn component * @param csrDomain string identifying the dns domain for generating SAN fields * @param expiryTime number of seconds to request certificate to be valid for * @return RoleCertificateRequest object *///w w w . ja v a 2s. c o m static public RoleCertificateRequest generateRoleCertificateRequest(final String principalDomain, final String principalService, final String roleDomainName, final String roleName, PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) { if (principalDomain == null || principalService == null) { throw new IllegalArgumentException("Principal's Domain and Service must be specified"); } if (roleDomainName == null || roleName == null) { throw new IllegalArgumentException("Role DomainName and Name must be specified"); } if (csrDomain == null) { throw new IllegalArgumentException("X509 CSR Domain must be specified"); } // Athenz uses lower case for all elements, so let's // generate our dn which will be our role resource value final String domain = principalDomain.toLowerCase(); final String service = principalService.toLowerCase(); String dn = "cn=" + roleDomainName.toLowerCase() + ":role." + roleName.toLowerCase(); if (csrDn != null) { dn = dn.concat(",").concat(csrDn); } // now let's generate our dsnName and email fields which will based on // our principal's details StringBuilder hostBuilder = new StringBuilder(128); hostBuilder.append(service); hostBuilder.append('.'); hostBuilder.append(domain.replace('.', '-')); hostBuilder.append('.'); hostBuilder.append(csrDomain); String hostName = hostBuilder.toString(); String email = domain + "." + service + "@" + csrDomain; GeneralName[] sanArray = new GeneralName[2]; sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName)); sanArray[1] = new GeneralName(GeneralName.rfc822Name, new DERIA5String(email)); String csr = null; try { csr = Crypto.generateX509CSR(privateKey, dn, sanArray); } catch (OperatorCreationException | IOException ex) { throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage()); } RoleCertificateRequest req = new RoleCertificateRequest().setCsr(csr) .setExpiryTime(Long.valueOf(expiryTime)); return req; }
From source file:com.yahoo.athenz.zts.ZTSClient.java
License:Apache License
/** * Generate a Instance Refresh request that could be sent to ZTS to * request a TLS certificate for a service. * @param principalDomain name of the principal's domain * @param principalService name of the principal's service * @param privateKey private key for the service identity for the caller * @param csrDn string identifying the dn for the csr without the cn component * @param csrDomain string identifying the dns domain for generating SAN fields * @param expiryTime number of seconds to request certificate to be valid for * @return InstanceRefreshRequest object *//* w w w. j a v a 2 s . co m*/ static public InstanceRefreshRequest generateInstanceRefreshRequest(final String principalDomain, final String principalService, PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) { if (principalDomain == null || principalService == null) { throw new IllegalArgumentException("Principal's Domain and Service must be specified"); } if (csrDomain == null) { throw new IllegalArgumentException("X509 CSR Domain must be specified"); } // Athenz uses lower case for all elements, so let's // generate our dn which will be based on our service name final String domain = principalDomain.toLowerCase(); final String service = principalService.toLowerCase(); final String cn = domain + "." + service; String dn = "cn=" + cn; if (csrDn != null) { dn = dn.concat(",").concat(csrDn); } // now let's generate our dsnName field based on our principal's details StringBuilder hostBuilder = new StringBuilder(128); hostBuilder.append(service); hostBuilder.append('.'); hostBuilder.append(domain.replace('.', '-')); hostBuilder.append('.'); hostBuilder.append(csrDomain); String hostName = hostBuilder.toString(); GeneralName[] sanArray = new GeneralName[1]; sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName)); String csr = null; try { csr = Crypto.generateX509CSR(privateKey, dn, sanArray); } catch (OperatorCreationException | IOException ex) { throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage()); } InstanceRefreshRequest req = new InstanceRefreshRequest().setCsr(csr) .setExpiryTime(Integer.valueOf(expiryTime)); return req; }
From source file:com.yahoo.athenz.zts.ZTSClient.java
License:Apache License
/** * For AWS Lambda functions generate a new private key, request a * x.509 certificate based on the requested CSR and return both to * the client in order to establish tls connections with other * Athenz enabled services.//from w ww .j a va 2 s. c o m * @param domainName name of the domain * @param serviceName name of the service * @param account AWS account name that the function runs in * @param provider name of the provider service for AWS Lambda * @return AWSLambdaIdentity with private key and certificate */ public AWSLambdaIdentity getAWSLambdaServiceCertificate(String domainName, String serviceName, String account, String provider) { if (domainName == null || serviceName == null) { throw new IllegalArgumentException("Domain and Service must be specified"); } if (account == null || provider == null) { throw new IllegalArgumentException("AWS Account and Provider must be specified"); } if (x509CsrDomain == null) { throw new IllegalArgumentException("X509 CSR Domain must be specified"); } // first we're going to generate a private key for the request AWSLambdaIdentity lambdaIdentity = new AWSLambdaIdentity(); try { lambdaIdentity.setPrivateKey(Crypto.generateRSAPrivateKey(2048)); } catch (CryptoException ex) { throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage()); } // we need to generate an csr with an instance register object InstanceRegisterInformation info = new InstanceRegisterInformation(); info.setDomain(domainName.toLowerCase()); info.setService(serviceName.toLowerCase()); info.setProvider(provider.toLowerCase()); final String athenzService = info.getDomain() + "." + info.getService(); // generate our dn which will be based on our service name StringBuilder dnBuilder = new StringBuilder(128); dnBuilder.append("cn="); dnBuilder.append(athenzService); if (x509CsrDn != null) { dnBuilder.append(','); dnBuilder.append(x509CsrDn); } // now let's generate our dsnName field based on our principal's details StringBuilder hostBuilder = new StringBuilder(128); hostBuilder.append(info.getService()); hostBuilder.append('.'); hostBuilder.append(info.getDomain().replace('.', '-')); hostBuilder.append('.'); hostBuilder.append(x509CsrDomain); StringBuilder instanceHostBuilder = new StringBuilder(128); instanceHostBuilder.append("lambda-"); instanceHostBuilder.append(account); instanceHostBuilder.append('-'); instanceHostBuilder.append(info.getService()); instanceHostBuilder.append(".instanceid.athenz."); instanceHostBuilder.append(x509CsrDomain); GeneralName[] sanArray = new GeneralName[2]; sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostBuilder.toString())); sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(instanceHostBuilder.toString())); // next generate the csr based on our private key and data try { info.setCsr(Crypto.generateX509CSR(lambdaIdentity.getPrivateKey(), dnBuilder.toString(), sanArray)); } catch (OperatorCreationException | IOException ex) { throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage()); } // finally obtain attestation data for lambda info.setAttestationData(getAWSLambdaAttestationData(athenzService, account)); // request the x.509 certificate from zts server Map<String, List<String>> responseHeaders = new HashMap<>(); InstanceIdentity identity = postInstanceRegisterInformation(info, responseHeaders); try { lambdaIdentity.setX509Certificate(Crypto.loadX509Certificate(identity.getX509Certificate())); } catch (CryptoException ex) { throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage()); } return lambdaIdentity; }
From source file:de.petendi.commons.crypto.connector.BCConnector.java
License:Apache License
@Override public X509Certificate createCertificate(String dn, String issuer, String crlUri, PublicKey publicKey, PrivateKey privateKey) throws CryptoException { Calendar date = Calendar.getInstance(); // Serial Number BigInteger serialNumber = BigInteger.valueOf(date.getTimeInMillis()); // Subject and Issuer DN X500Name subjectDN = new X500Name(dn); X500Name issuerDN = new X500Name(issuer); // Validity/*from w ww . j a va 2 s . c o m*/ Date notBefore = date.getTime(); date.add(Calendar.YEAR, 20); Date notAfter = date.getTime(); // SubjectPublicKeyInfo SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(publicKey.getEncoded())); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo); DigestCalculator digCalc = null; try { digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc); // Subject Key Identifier certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo)); // Authority Key Identifier certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo)); // Key Usage certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.dataEncipherment)); if (crlUri != null) { // CRL Distribution Points DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, crlUri))); DistributionPoint[] distPoints = new DistributionPoint[1]; distPoints[0] = new DistributionPoint(distPointOne, null, null); certGen.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints)); } // Content Signer ContentSigner sigGen = new JcaContentSignerBuilder(getSignAlgorithm()).setProvider(getProviderName()) .build(privateKey); // Certificate return new JcaX509CertificateConverter().setProvider(getProviderName()) .getCertificate(certGen.build(sigGen)); } catch (Exception e) { throw new CryptoException(e); } }
From source file:esteidhacker.FakeEstEIDCA.java
License:Open Source License
public X509Certificate generateUserCertificate(RSAPublicKey pubkey, boolean signature, String firstname, String lastname, String idcode, String email) throws InvalidKeyException, ParseException, IOException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException { Date startDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2015-01-01"); Date endDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2015-12-31"); String template = "C=EE,O=ESTEID,OU=%s,CN=%s\\,%s\\,%s,SURNAME=%s,GIVENNAME=%s,SERIALNUMBER=%s"; // Normalize. lastname = lastname.toUpperCase();// w ww. java2s . com firstname = firstname.toUpperCase(); idcode = idcode.toUpperCase(); email = email.toLowerCase(); String subject = String.format(template, (signature ? "digital signature" : "authentication"), lastname, firstname, idcode, lastname, firstname, idcode); byte[] serialBytes = new byte[16]; SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG"); rnd.nextBytes(serialBytes); serialBytes[0] &= 0x7F; // Can't be negative BigInteger serial = new BigInteger(serialBytes); X509CertificateHolder real; if (signature) { real = getRealCert("/resources/sk-sign.pem"); } else { real = getRealCert("/resources/sk-auth.pem"); } serial = real.getSerialNumber(); System.out.println("Generating from subject: " + real.getSubject()); System.out.println("Generating subject: " + new X500Name(subject).toString()); JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(real.getIssuer(), serial, startDate, endDate, new X500Name(subject), pubkey); @SuppressWarnings("unchecked") List<ASN1ObjectIdentifier> list = real.getExtensionOIDs(); // Copy all extensions, except altName for (ASN1ObjectIdentifier extoid : list) { Extension ext = real.getExtension(extoid); if (ext.getExtnId().equals(Extension.subjectAlternativeName)) { // altName must be changed builder.addExtension(ext.getExtnId(), ext.isCritical(), new GeneralNames(new GeneralName(GeneralName.rfc822Name, email))); } else { builder.copyAndAddExtension(ext.getExtnId(), ext.isCritical(), real); } } // Generate cert ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(esteidKey); X509CertificateHolder cert = builder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(cert); }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.GWCertificateUtilsBc.java
License:Apache License
/** * /*from ww w .java2 s . c o m*/ * @param entityKey - public key of the requesting GW * @param caKey * @param caCert * @return * @throws Exception */ public static X509CertificateHolder buildEndEntityCert(X500Name subject, AsymmetricKeyParameter entityKey, AsymmetricKeyParameter caKey, X509CertificateHolder caCert, String ufn) throws Exception { SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(entityKey); if (subject == null) subject = new X500Name("CN = BETaaS Gateway Certificate"); X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD), subject, entityKeyInfo); X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator()); certBldr.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(entityKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)) .addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, ufn))); AlgorithmIdentifier sigAlg = algFinder.find(ALG_NAME); AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg); ContentSigner signer = new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(caKey); return certBldr.build(signer); }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.GWCertificateUtilsBc.java
License:Apache License
/** * A method to build PKCS10 Certification request (BC style) * @param subject: the subject info/data in X500Name format * @param kp: the subject's key pair/* w w w. j a v a 2 s. co m*/ * @param subjectAltName: subject's UFN * @return * @throws Exception */ public static PKCS10CertificationRequest buildCertificateRequest(X500Name subject, AsymmetricCipherKeyPair kp, String subjectAltName) throws Exception { String sigName = "SHA1withECDSA"; SignatureAlgorithmIdentifierFinder algFinder = new DefaultSignatureAlgorithmIdentifierFinder(); PKCS10CertificationRequestBuilder requestBuilder = new BcPKCS10CertificationRequestBuilder(subject, kp.getPublic()); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, subjectAltName + "@betaas.eu"))); requestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()); AlgorithmIdentifier sigAlg = algFinder.find(sigName); AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg); ContentSigner signer = new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(kp.getPrivate()); PKCS10CertificationRequest req1 = requestBuilder.build(signer); return req1; }
From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java
License:Open Source License
private void checkNameConstraints() { X509Certificate cert = null;//from w w w.j a v a 2 s.co m // // Setup // // (b) and (c) PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator(); // // process each certificate except the self issued which are not last in the path // int index; try { for (index = certs.size() - 1; index >= 0; index--) { // // certificate processing // cert = (X509Certificate) certs.get(index); // b),c) if (!(isSelfIssued(cert) && index != 0)) { X500Principal principal = getSubjectPrincipal(cert); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(principal.getEncoded())); ASN1Sequence dns; try { dns = (ASN1Sequence) aIn.readObject(); } catch (IOException e) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncSubjectNameError", new Object[] { new UntrustedInput(principal) }); throw new CertPathReviewerException(msg, e, certPath, index); } try { nameConstraintValidator.checkPermittedDN(dns); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } try { nameConstraintValidator.checkExcludedDN(dns); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } //FIX (missing in orig cert path reviewer) Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress); for (Enumeration e = emails.elements(); e.hasMoreElements();) { String email = (String) e.nextElement(); GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email); try { nameConstraintValidator.checkPermitted(emailAsGeneralName); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } try { nameConstraintValidator.checkExcluded(emailAsGeneralName); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } } ASN1Sequence altName; try { altName = (ASN1Sequence) getExtensionValue(cert, SUBJECT_ALTERNATIVE_NAME); } catch (AnnotatedException ae) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.subjAltNameExtError"); throw new CertPathReviewerException(msg, ae, certPath, index); } if (altName != null) { for (int j = 0; j < altName.size(); j++) { GeneralName name = GeneralName.getInstance(altName.getObjectAt(j)); try { nameConstraintValidator.checkPermitted(name); nameConstraintValidator.checkExcluded(name); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedEmail", new Object[] { new UntrustedInput(name) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } } } } // // prepare for next certificate // // // (g) handle the name constraints extension // ASN1Sequence ncSeq; try { ncSeq = (ASN1Sequence) getExtensionValue(cert, NAME_CONSTRAINTS); } catch (AnnotatedException ae) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncExtError"); throw new CertPathReviewerException(msg, ae, certPath, index); } if (ncSeq != null) { NameConstraints nc = NameConstraints.getInstance(ncSeq); // // (g) (1) permitted subtrees // GeneralSubtree[] permitted = nc.getPermittedSubtrees(); if (permitted != null) { nameConstraintValidator.intersectPermittedSubtree(permitted); } // // (g) (2) excluded subtrees // GeneralSubtree[] excluded = nc.getExcludedSubtrees(); if (excluded != null) { for (int c = 0; c != excluded.length; c++) { nameConstraintValidator.addExcludedSubtree(excluded[c]); } } } } // for } catch (CertPathReviewerException cpre) { addError(cpre.getErrorMessage(), cpre.getIndex()); } }