org.bouncycastle.asn1.x500.X500Name Java Examples
The following examples show how to use
org.bouncycastle.asn1.x500.X500Name.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SelfSignedCertBuilder.java From xipki with Apache License 2.0 | 6 votes |
private static void addExtensions(X509v3CertificateBuilder certBuilder, IdentifiedCertprofile profile, X500Name requestedSubject, X500Name grantedSubject, Extensions extensions, SubjectPublicKeyInfo requestedPublicKeyInfo, PublicCaInfo publicCaInfo, Date notBefore, Date notAfter) throws CertprofileException, IOException, BadCertTemplateException { ExtensionValues extensionTuples = profile.getExtensions(requestedSubject, grantedSubject, extensions, requestedPublicKeyInfo, publicCaInfo, null, notBefore, notAfter); if (extensionTuples == null) { return; } for (ASN1ObjectIdentifier extType : extensionTuples.getExtensionTypes()) { ExtensionValue extValue = extensionTuples.getExtensionValue(extType); certBuilder.addExtension(extType, extValue.isCritical(), extValue.getValue()); } }
Example #2
Source File: SM2Pkcs12MakerTest.java From gmhelper with Apache License 2.0 | 6 votes |
@Test public void testMakePkcs12() { try { KeyPair subKP = SM2Util.generateKeyPair(); X500Name subDN = SM2X509CertMakerTest.buildSubjectDN(); SM2PublicKey sm2SubPub = new SM2PublicKey(subKP.getPublic().getAlgorithm(), (BCECPublicKey) subKP.getPublic()); byte[] csr = CommonUtil.createCSR(subDN, sm2SubPub, subKP.getPrivate(), SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2).getEncoded(); SM2X509CertMaker certMaker = SM2X509CertMakerTest.buildCertMaker(); X509Certificate cert = certMaker.makeSSLEndEntityCert(csr); SM2Pkcs12Maker pkcs12Maker = new SM2Pkcs12Maker(); KeyStore pkcs12 = pkcs12Maker.makePkcs12(subKP.getPrivate(), cert, TEST_P12_PASSWD); try (OutputStream os = Files.newOutputStream(Paths.get(TEST_P12_FILENAME), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { pkcs12.store(os, TEST_P12_PASSWD); } } catch (Exception ex) { ex.printStackTrace(); Assert.fail(); } }
Example #3
Source File: CaManagerImpl.java From xipki with Apache License 2.0 | 6 votes |
@Override public CertWithRevocationInfo getCert(X500Name issuer, BigInteger serialNumber) throws CaMgmtException { Args.notNull(issuer, "issuer"); Args.notNull(serialNumber, "serialNumber"); NameId caId = null; for (String name : caInfos.keySet()) { CaInfo ca = caInfos.get(name); if (issuer.equals(caInfos.get(name).getCert().getSubject())) { caId = ca.getIdent(); break; } } if (caId == null) { return null; } try { return certstore.getCertWithRevocationInfo(caId.getId(), serialNumber, idNameMap); } catch (OperationException ex) { throw new CaMgmtException(ex.getMessage(), ex); } }
Example #4
Source File: PGPEncryptionUtil.java From peer-os with Apache License 2.0 | 6 votes |
public static X509Certificate getX509CertificateFromPgpKeyPair( PGPPublicKey pgpPublicKey, PGPSecretKey pgpSecretKey, String secretPwd, String issuer, String subject, Date dateOfIssue, Date dateOfExpiry, BigInteger serial ) throws PGPException, CertificateException, IOException { JcaPGPKeyConverter c = new JcaPGPKeyConverter(); PublicKey publicKey = c.getPublicKey( pgpPublicKey ); PrivateKey privateKey = c.getPrivateKey( pgpSecretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ) ); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name( issuer ), serial, dateOfIssue, dateOfExpiry, new X500Name( subject ), SubjectPublicKeyInfo.getInstance( publicKey.getEncoded() ) ); byte[] certBytes = certBuilder.build( new JCESigner( privateKey, "SHA256withRSA" ) ).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance( "X.509" ); return ( X509Certificate ) certificateFactory.generateCertificate( new ByteArrayInputStream( certBytes ) ); }
Example #5
Source File: SigningCertificate.java From signer with GNU Lesser General Public License v3.0 | 6 votes |
@Override public Attribute getValue() { try { X509Certificate cert = (X509Certificate) certificates[0]; Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_1); byte[] hash = digest.digest(cert.getEncoded()); X500Name dirName = new X500Name(cert.getSubjectDN().getName()); GeneralName name = new GeneralName(dirName); GeneralNames issuer = new GeneralNames(name); ASN1Integer serial = new ASN1Integer(cert.getSerialNumber()); IssuerSerial issuerSerial = new IssuerSerial(issuer, serial); ESSCertID essCertId = new ESSCertID(hash, issuerSerial); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)}))); } catch (CertificateEncodingException ex) { throw new SignerException(ex.getMessage()); } }
Example #6
Source File: KeyGenerator.java From chvote-1-0 with GNU Affero General Public License v3.0 | 6 votes |
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY)); nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY)); nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY)); nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY)); X500Name x500Name = nameBuilder.build(); BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS)); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo); String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY); certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName)); return certificateBuilder; }
Example #7
Source File: Crypto.java From athenz with Apache License 2.0 | 6 votes |
public static String extractX509CertSubjectField(X509Certificate x509Cert, ASN1ObjectIdentifier id) { String principalName = x509Cert.getSubjectX500Principal().getName(); ///CLOVER:OFF if (principalName == null || principalName.isEmpty()) { return null; } ///CLOVER:ON X500Name x500name = new X500Name(principalName); RDN[] rdns = x500name.getRDNs(id); // we're only supporting a single field in Athenz certificates so // any other multiple value will be considered invalid if (rdns == null || rdns.length == 0) { return null; } ///CLOVER:OFF if (rdns.length != 1) { throw new CryptoException("CSR Subject contains multiple values for the same field."); } ///CLOVER:ON return IETFUtils.valueToString(rdns[0].getFirst().getValue()); }
Example #8
Source File: SSLKeyPairCerts.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception { final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( new org.bouncycastle.asn1.x500.X500Name(certSub), BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(certSub), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) ); final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames); final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption"); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); final ContentSigner signer = signerBuilder.build(keyp); final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer); final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder); certificate.checkValidity(new Date()); certificate.verify(keyPair.getPublic()); return certificate; }
Example #9
Source File: CryptoTest.java From athenz with Apache License 2.0 | 6 votes |
@Test public void testGenerateX509CertificateInvalid() throws IOException { Path path = Paths.get("src/test/resources/valid.csr"); String certStr = new String(Files.readAllBytes(path)); PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(certStr); PrivateKey caPrivateKey = Crypto.loadPrivateKey(rsaPrivateKey); try { Crypto.generateX509Certificate(certReq, caPrivateKey, (X500Name) null, 600, true); fail(); } catch (CryptoException ex) { assertTrue(true, "Caught excepted exception"); } }
Example #10
Source File: CommonUtil.java From gmhelper with Apache License 2.0 | 6 votes |
/** * 如果不知道怎么填充names,可以查看org.bouncycastle.asn1.x500.style.BCStyle这个类, * names的key值必须是BCStyle.DefaultLookUp中存在的(可以不关心大小写) * * @param names * @return * @throws InvalidX500NameException */ public static X500Name buildX500Name(Map<String, String> names) throws InvalidX500NameException { if (names == null || names.size() == 0) { throw new InvalidX500NameException("names can not be empty"); } try { X500NameBuilder builder = new X500NameBuilder(); Iterator itr = names.entrySet().iterator(); BCStyle x500NameStyle = (BCStyle) BCStyle.INSTANCE; Map.Entry entry; while (itr.hasNext()) { entry = (Map.Entry) itr.next(); ASN1ObjectIdentifier oid = x500NameStyle.attrNameToOID((String) entry.getKey()); builder.addRDN(oid, (String) entry.getValue()); } return builder.build(); } catch (Exception ex) { throw new InvalidX500NameException(ex.getMessage(), ex); } }
Example #11
Source File: CmpClientImpl.java From xipki with Apache License 2.0 | 6 votes |
@Override public String getCaNameByIssuer(X500Name issuer) throws CmpClientException { Args.notNull(issuer, "issuer"); initIfNotInitialized(); for (String name : casMap.keySet()) { final CaConf ca = casMap.get(name); if (!ca.isCaInfoConfigured()) { continue; } if (CompareUtil.equalsObject(ca.getSubject(), issuer)) { return name; } } throw new CmpClientException("unknown CA for issuer: " + issuer); }
Example #12
Source File: TlsHelper.java From nifi with Apache License 2.0 | 6 votes |
public static Extensions createDomainAlternativeNamesExtensions(List<String> domainAlternativeNames, String requestedDn) throws IOException { List<GeneralName> namesList = new ArrayList<>(); try { final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue()); namesList.add(new GeneralName(GeneralName.dNSName, cn)); } catch (Exception e) { throw new IOException("Failed to extract CN from request DN: " + requestedDn, e); } if (domainAlternativeNames != null) { for (String alternativeName : domainAlternativeNames) { namesList.add(new GeneralName(IPAddress.isValid(alternativeName) ? GeneralName.iPAddress : GeneralName.dNSName, alternativeName)); } } GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[]{})); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); return extGen.generate(); }
Example #13
Source File: LdapAuthenticator.java From keywhiz with Apache License 2.0 | 6 votes |
private Set<String> rolesFromDN(String userDN) throws LDAPException, GeneralSecurityException { SearchRequest searchRequest = new SearchRequest(config.getRoleBaseDN(), SearchScope.SUB, Filter.createEqualityFilter("uniqueMember", userDN)); Set<String> roles = Sets.newLinkedHashSet(); LDAPConnection connection = connectionFactory.getLDAPConnection(); try { SearchResult sr = connection.search(searchRequest); for (SearchResultEntry sre : sr.getSearchEntries()) { X500Name x500Name = new X500Name(sre.getDN()); RDN[] rdns = x500Name.getRDNs(BCStyle.CN); if (rdns.length == 0) { logger.error("Could not create X500 Name for role:" + sre.getDN()); } else { String commonName = IETFUtils.valueToString(rdns[0].getFirst().getValue()); roles.add(commonName); } } } finally { connection.close(); } return roles; }
Example #14
Source File: X509Ca.java From xipki with Apache License 2.0 | 6 votes |
public RequestorInfo.CmpRequestorInfo getRequestor(X500Name requestorSender) { Set<MgmtEntry.CaHasRequestor> requestorEntries = caManager.getRequestorsForCa(caIdent.getName()); if (CollectionUtil.isEmpty(requestorEntries)) { return null; } for (MgmtEntry.CaHasRequestor m : requestorEntries) { RequestorEntryWrapper entry = caManager.getRequestorWrapper(m.getRequestorIdent().getName()); if (entry.getDbEntry().isFaulty()) { continue; } if (!MgmtEntry.Requestor.TYPE_CERT.equals(entry.getDbEntry().getType())) { continue; } if (entry.getCert().getCert().getSubject().equals(requestorSender)) { return new RequestorInfo.CmpRequestorInfo(m, entry.getCert()); } } return null; }
Example #15
Source File: IdentityCertificateService.java From flashback with BSD 2-Clause "Simplified" License | 6 votes |
/** * Create a certificate using key pair and signing certificate with CA certificate, common name and a list of subjective alternate name * * @return signed sever identity certificate * */ @Override public X509Certificate createSignedCertificate(PublicKey publicKey, PrivateKey privateKey, String commonName, List<ASN1Encodable> sans) throws CertificateException, IOException, OperatorCreationException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { X500Name issuer = new X509CertificateHolder(_issuerCertificate.getEncoded()).getSubject(); BigInteger serial = getSerial(); X500Name subject = getSubject(commonName); X509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder(issuer, serial, getValidDateFrom(), getValidDateTo(), subject, publicKey); buildExtensions(x509v3CertificateBuilder, publicKey); fillSans(sans, x509v3CertificateBuilder); X509Certificate signedCertificate = createCertificate(_issuerPrivateKey, x509v3CertificateBuilder); signedCertificate.checkValidity(); signedCertificate.verify(_issuerCertificate.getPublicKey()); return signedCertificate; }
Example #16
Source File: RsaSsaPss.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * create a basic X509 certificate from the given keys */ static X509Certificate makeCertificate( KeyPair subKP, String subDN, KeyPair issKP, String issDN) throws GeneralSecurityException, IOException, OperatorCreationException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name(issDN), BigInteger.valueOf(serialNo++), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(subDN), subPub); v3CertGen.addExtension( X509Extension.subjectKeyIdentifier, false, createSubjectKeyId(subPub)); v3CertGen.addExtension( X509Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issPub)); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(issPriv))); }
Example #17
Source File: TLSCertificateBuilder.java From fabric-sdk-java with Apache License 2.0 | 6 votes |
private X509v3CertificateBuilder createCertBuilder(KeyPair keyPair) { X500Name subject = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.CN, commonName) .build(); Calendar notBefore = new GregorianCalendar(); notBefore.add(Calendar.DAY_OF_MONTH, -1); Calendar notAfter = new GregorianCalendar(); notAfter.add(Calendar.YEAR, 10); return new JcaX509v3CertificateBuilder( subject, new BigInteger(160, rand), notBefore.getTime(), notAfter.getTime(), subject, keyPair.getPublic()); }
Example #18
Source File: CertificateUtils.java From localization_nifi with Apache License 2.0 | 5 votes |
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate */ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #19
Source File: Actions.java From xipki with Apache License 2.0 | 5 votes |
private PKCS10CertificationRequest generateRequest(ConcurrentContentSigner signer, SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn, Map<ASN1ObjectIdentifier, ASN1Encodable> attributes) throws XiSecurityException { Args.notNull(signer, "signer"); Args.notNull(subjectPublicKeyInfo, "subjectPublicKeyInfo"); Args.notNull(subjectDn, "subjectDn"); PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo); if (CollectionUtil.isNotEmpty(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); } }
Example #20
Source File: CertificateUtils.java From nifi-registry with Apache License 2.0 | 5 votes |
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate */ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #21
Source File: CmpClientImpl.java From xipki with Apache License 2.0 | 5 votes |
@Override public Map<String, CertIdOrError> revokeCerts(RevokeCertRequest request, ReqRespDebug debug) throws CmpClientException, PkiErrorException { List<RevokeCertRequest.Entry> requestEntries = Args.notNull(request, "request").getRequestEntries(); if (CollectionUtil.isEmpty(requestEntries)) { return Collections.emptyMap(); } X500Name issuer = requestEntries.get(0).getIssuer(); for (int i = 1; i < requestEntries.size(); i++) { if (!issuer.equals(requestEntries.get(i).getIssuer())) { throw new PkiErrorException(PKIStatus.REJECTION, PKIFailureInfo.badRequest, "revoking certificates issued by more than one CA is not allowed"); } } initIfNotInitialized(); final String caName = getCaNameByIssuer(issuer); CaConf caConf = casMap.get(caName); if (caConf.getCmpControl().isRrAkiRequired()) { byte[] aki = caConf.getSubjectKeyIdentifier(); List<RevokeCertRequest.Entry> entries = request.getRequestEntries(); for (RevokeCertRequest.Entry entry : entries) { if (entry.getAuthorityKeyIdentifier() == null) { entry.setAuthorityKeyIdentifier(aki); } } } RevokeCertResponse result = caConf.getAgent().revokeCertificate(request, debug); return parseRevokeCertResult(result); }
Example #22
Source File: SubjectChecker.java From xipki with Apache License 2.0 | 5 votes |
private ValidationIssue checkSubjectAttribute(ASN1ObjectIdentifier type, X500Name subject, X500Name requestedSubject) throws BadCertTemplateException { boolean multiValuedRdn = subjectControl.getGroup(type) != null; if (multiValuedRdn) { return checkSubjectAttributeMultiValued(type, subject, requestedSubject); } else { return checkSubjectAttributeNotMultiValued(type, subject, requestedSubject); } }
Example #23
Source File: X509Ca.java From xipki with Apache License 2.0 | 5 votes |
public GrantedCertTemplate(Extensions extensions, IdentifiedCertprofile certprofile, Date grantedNotBefore, Date grantedNotAfter, X500Name requestedSubject, SubjectPublicKeyInfo grantedPublicKey, PrivateKeyInfo privateKey, ConcurrentContentSigner signer, String warning) { this.extensions = extensions; this.certprofile = certprofile; this.grantedNotBefore = grantedNotBefore; this.grantedNotAfter = grantedNotAfter; this.requestedSubject = requestedSubject; this.grantedPublicKey = grantedPublicKey; this.privateKey = privateKey; this.signer = signer; this.warning = warning; }
Example #24
Source File: RevokeCertRequest.java From xipki with Apache License 2.0 | 5 votes |
public Entry(String id, X500Name issuer, BigInteger serialNumber, int reason, Date invalidityDate) { super(id, issuer, serialNumber); if (!(reason >= 0 && reason <= 10 && reason != 7)) { throw new IllegalArgumentException("invalid reason: " + reason); } this.reason = reason; this.invalidityDate = invalidityDate; }
Example #25
Source File: CryptoTest.java From athenz with Apache License 2.0 | 5 votes |
@Test public void testExtractX509CSRSubjectFieldNull() { PKCS10CertificationRequest certReq = mock(PKCS10CertificationRequest.class); when(certReq.getSubject()).thenReturn(null); assertNull(Crypto.extractX509CSRSubjectField(certReq, null)); X500Name x500Name = mock(X500Name.class); when(certReq.getSubject()).thenReturn(x500Name); RDN[] rdns = new RDN[2]; when(x500Name.getRDNs(null)).thenReturn(rdns); assertThrows(CryptoException.class, () -> { Crypto.extractX509CSRSubjectField(certReq, null); }); }
Example #26
Source File: ClientFingerprintTrustManager.java From incubator-tuweni with Apache License 2.0 | 5 votes |
@Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { X509Certificate cert = chain[0]; X500Name x500name = new JcaX509CertificateHolder(cert).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String hostname = IETFUtils.valueToString(cn.getFirst().getValue()); checkTrusted(chain, hostname); }
Example #27
Source File: Certificates.java From vertx-config with Apache License 2.0 | 5 votes |
/** * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder * * @param keyPair The RSA keypair with which to generate the certificate * @param issuer The issuer (and subject) to use for the certificate * @return An X509 certificate * @throws IOException * @throws OperatorCreationException * @throws CertificateException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException */ private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { final String subject = issuer; final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( new X500Name(issuer), BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(subject), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) ); final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames); final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption"); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); final ContentSigner signer = signerBuilder.build(keyp); final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(x509CertificateHolder); certificate.checkValidity(new Date()); certificate.verify(keyPair.getPublic()); return certificate; }
Example #28
Source File: DViewCsr.java From keystore-explorer with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); KeyPair keyPair = keyGen.genKeyPair(); JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder( new X500Name("cn=test"), keyPair.getPublic()); PKCS10CertificationRequest csr = csrBuilder .build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(keyPair.getPrivate())); DViewCsr dialog = new DViewCsr(new javax.swing.JFrame(), "Title", csr); DialogViewer.run(dialog); }
Example #29
Source File: OcspRef.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private String getResponderIdByName() { RespID responderId = this.ocsp.getResponderId(); ResponderID responderIdAsASN1Object = responderId.toASN1Primitive(); DERTaggedObject derTaggedObject = (DERTaggedObject)responderIdAsASN1Object.toASN1Primitive(); if (2 == derTaggedObject.getTagNo()) { return null; } else { ASN1Primitive derObject = derTaggedObject.getObject(); X500Name name = X500Name.getInstance(derObject); return RFC2253Parser.normalize(name.toString()); } }
Example #30
Source File: OcspRef.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private String getResponderIdByName() { RespID responderId = this.ocsp.getResponderId(); ResponderID responderIdAsASN1Object = responderId.toASN1Primitive(); DERTaggedObject derTaggedObject = (DERTaggedObject)responderIdAsASN1Object.toASN1Primitive(); if (2 == derTaggedObject.getTagNo()) { return null; } else { ASN1Primitive derObject = derTaggedObject.getObject(); X500Name name = X500Name.getInstance(derObject); return RFC2253Parser.normalize(name.toString()); } }