Java Code Examples for org.bouncycastle.asn1.x500.X500Name

The following examples show how to use org.bouncycastle.asn1.x500.X500Name. These examples are extracted from open source projects. 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 Project: fabric-sdk-java   Source File: TLSCertificateBuilder.java    License: Apache License 2.0 6 votes vote down vote up
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 2
Source Project: xipki   Source File: X509Ca.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: xipki   Source File: CmpClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
@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 5
Source Project: peer-os   Source File: PGPEncryptionUtil.java    License: Apache License 2.0 6 votes vote down vote up
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 6
Source Project: xipki   Source File: CaManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: athenz   Source File: Crypto.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: athenz   Source File: CryptoTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: keywhiz   Source File: LdapAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
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 10
Source Project: gmhelper   Source File: CommonUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 如果不知道怎么填充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 Project: vertx-tcp-eventbus-bridge   Source File: SSLKeyPairCerts.java    License: Apache License 2.0 6 votes vote down vote up
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 12
Source Project: gmhelper   Source File: SM2Pkcs12MakerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
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 14
Source Project: nifi   Source File: TlsHelper.java    License: Apache License 2.0 6 votes vote down vote up
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 15
/**
 * 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
/**
 * 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 Project: xipki   Source File: SelfSignedCertBuilder.java    License: Apache License 2.0 6 votes vote down vote up
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 18
Source Project: xipki   Source File: CmpAgent.java    License: Apache License 2.0 5 votes vote down vote up
CmpAgent(Requestor requestor, Responder responder,
    String serverUrl, SecurityFactory securityFactory,
    SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier) {

  this.requestor = Args.notNull(requestor, "requestor");
  this.responder = Args.notNull(responder, "responder");
  this.securityFactory = Args.notNull(securityFactory, "securityFactory");
  Args.notBlank(serverUrl, "serverUrl");

  boolean bothSignatureBased = (requestor instanceof Requestor.SignatureCmpRequestor)
      && (responder instanceof Responder.SignaturetCmpResponder);
  boolean bothMacBased = (requestor instanceof Requestor.PbmMacCmpRequestor
      && responder instanceof Responder.PbmMacCmpResponder);
  if (!(bothSignatureBased || bothMacBased)) {
    throw new IllegalArgumentException("requestor and responder do not match");
  }

  this.recipientName = (X500Name) responder.getName().getName();

  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  try {
    this.serverUrl = new URL(serverUrl);
  } catch (MalformedURLException ex) {
    throw new IllegalArgumentException("invalid URL: " + serverUrl);
  }
}
 
Example 19
@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 20
Source Project: xipki   Source File: Requestor.java    License: Apache License 2.0 5 votes vote down vote up
private static X500Name getSignerSubject(ConcurrentContentSigner signer) {
  Args.notNull(signer, "signer");
  if (signer.getCertificate() == null) {
    throw new IllegalArgumentException("requestor without certificate is not allowed");
  }

  return signer.getCertificate().getSubject();
}
 
Example 21
Source Project: xipki   Source File: X509Ca.java    License: Apache License 2.0 5 votes vote down vote up
private static X500Name removeEmptyRdns(X500Name name) {
  RDN[] rdns = name.getRDNs();
  List<RDN> tmpRdns = new ArrayList<>(rdns.length);
  boolean changed = false;
  for (RDN rdn : rdns) {
    String textValue = X509Util.rdnValueToString(rdn.getFirst().getValue());
    if (StringUtil.isBlank(textValue)) {
      changed = true;
    } else {
      tmpRdns.add(rdn);
    }
  }

  return changed ? new X500Name(tmpRdns.toArray(new RDN[0])) : name;
}
 
Example 22
Source Project: hadoop-ozone   Source File: TestSecureOzoneCluster.java    License: Apache License 2.0 5 votes vote down vote up
public void validateCertificate(X509Certificate cert) throws Exception {

    // Assert that we indeed have a self signed certificate.
    X500Name x500Issuer = new JcaX509CertificateHolder(cert).getIssuer();
    RDN cn = x500Issuer.getRDNs(BCStyle.CN)[0];
    String hostName = InetAddress.getLocalHost().getHostName();
    String scmUser = "[email protected]" + hostName;
    assertEquals(scmUser, cn.getFirst().getValue().toString());

    // Subject name should be om login user in real world but in this test
    // UGI has scm user context.
    assertEquals(scmUser, cn.getFirst().getValue().toString());

    LocalDate today = LocalDateTime.now().toLocalDate();
    Date invalidDate;

    // Make sure the end date is honored.
    invalidDate = java.sql.Date.valueOf(today.plus(1, ChronoUnit.DAYS));
    assertTrue(cert.getNotAfter().after(invalidDate));

    invalidDate = java.sql.Date.valueOf(today.plus(400, ChronoUnit.DAYS));
    assertTrue(cert.getNotAfter().before(invalidDate));

    assertTrue(cert.getSubjectDN().toString().contains(scmId));
    assertTrue(cert.getSubjectDN().toString().contains(clusterId));

    assertTrue(cert.getIssuerDN().toString().contains(scmUser));
    assertTrue(cert.getIssuerDN().toString().contains(scmId));
    assertTrue(cert.getIssuerDN().toString().contains(clusterId));

    // Verify that certificate matches the public key.
    String encodedKey1 = cert.getPublicKey().toString();
    String encodedKey2 = om.getCertificateClient().getPublicKey().toString();
    assertEquals(encodedKey1, encodedKey2);
  }
 
Example 23
Source Project: xipki   Source File: BaseCmpResponder.java    License: Apache License 2.0 5 votes vote down vote up
private static X500Name getX500Sender(PKIHeader reqHeader) {
  GeneralName requestSender = reqHeader.getSender();
  if (requestSender.getTagNo() != GeneralName.directoryName) {
    return null;
  }

  return (X500Name) requestSender.getName();
}
 
Example 24
Source Project: xipki   Source File: CaClientExample.java    License: Apache License 2.0 5 votes vote down vote up
protected static CertificationRequest genCsr(MyKeypair keypair, String subject,
    String challengePassword) throws GeneralSecurityException, OperatorCreationException {
  X500Name subjectDn = new X500Name(subject);

  PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(
      subjectDn, keypair.publicKeyInfo);

  if (challengePassword != null && !challengePassword.isEmpty()) {
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
        new DERPrintableString(challengePassword));
  }

  ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
  return csrBuilder.build(signer).toASN1Structure();
}
 
Example 25
Source Project: Dream-Catcher   Source File: BouncyCastleSecurityProviderTool.java    License: MIT License 5 votes vote down vote up
/**
 * Creates an X500Name based on the specified certificateInfo.
 *
 * @param certificateInfo information to populate the X500Name with
 * @return a new X500Name object for use as a subject or issuer
 */
private static X500Name createX500NameForCertificate(CertificateInfo certificateInfo) {
    X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);

    if (certificateInfo.getCommonName() != null) {
        x500NameBuilder.addRDN(BCStyle.CN, certificateInfo.getCommonName());
    }

    if (certificateInfo.getOrganization() != null) {
        x500NameBuilder.addRDN(BCStyle.O, certificateInfo.getOrganization());
    }

    if (certificateInfo.getOrganizationalUnit() != null) {
        x500NameBuilder.addRDN(BCStyle.OU, certificateInfo.getOrganizationalUnit());
    }

    if (certificateInfo.getEmail() != null) {
        x500NameBuilder.addRDN(BCStyle.E, certificateInfo.getEmail());
    }

    if (certificateInfo.getLocality() != null) {
        x500NameBuilder.addRDN(BCStyle.L, certificateInfo.getLocality());
    }

    if (certificateInfo.getState() != null) {
        x500NameBuilder.addRDN(BCStyle.ST, certificateInfo.getState());
    }

    if (certificateInfo.getCountryCode() != null) {
        x500NameBuilder.addRDN(BCStyle.C, certificateInfo.getCountryCode());
    }

    // TODO: Add more X.509 certificate fields as needed

    return x500NameBuilder.build();
}
 
Example 26
/**
 * Creates an X500Name based on the specified certificateInfo.
 *
 * @param certificateInfo information to populate the X500Name with
 * @return a new X500Name object for use as a subject or issuer
 */
private static X500Name createX500NameForCertificate(CertificateInfo certificateInfo) {
    X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);

    if (certificateInfo.getCommonName() != null) {
        x500NameBuilder.addRDN(BCStyle.CN, certificateInfo.getCommonName());
    }

    if (certificateInfo.getOrganization() != null) {
        x500NameBuilder.addRDN(BCStyle.O, certificateInfo.getOrganization());
    }

    if (certificateInfo.getOrganizationalUnit() != null) {
        x500NameBuilder.addRDN(BCStyle.OU, certificateInfo.getOrganizationalUnit());
    }

    if (certificateInfo.getEmail() != null) {
        x500NameBuilder.addRDN(BCStyle.E, certificateInfo.getEmail());
    }

    if (certificateInfo.getLocality() != null) {
        x500NameBuilder.addRDN(BCStyle.L, certificateInfo.getLocality());
    }

    if (certificateInfo.getState() != null) {
        x500NameBuilder.addRDN(BCStyle.ST, certificateInfo.getState());
    }

    if (certificateInfo.getCountryCode() != null) {
        x500NameBuilder.addRDN(BCStyle.C, certificateInfo.getCountryCode());
    }

    // TODO: Add more X.509 certificate fields as needed

    return x500NameBuilder.build();
}
 
Example 27
private Certificate generateCertWithExtension() throws Exception {
    final KeyPair keyPair = createKeyPair();

    final JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
            new X500Name("CN=Test commonName"),
            BigInteger.valueOf(123456789),
            new Date(System.currentTimeMillis() - 10000),
            new Date(System.currentTimeMillis() + 10000),
            new X500Name("CN=Test commonName"),
            keyPair.getPublic()
    );

    certificateBuilder.addExtension(BCStyle.C, false, new DERUTF8String("DE"));
    certificateBuilder.addExtension(BCStyle.O, false, new DERUTF8String("Test organization"));
    certificateBuilder.addExtension(BCStyle.OU, false, new DERUTF8String("Test Unit"));
    certificateBuilder.addExtension(BCStyle.T, false, new DERUTF8String("Test Title"));
    certificateBuilder.addExtension(BCStyle.L, false, new DERUTF8String("Test locality"));
    certificateBuilder.addExtension(BCStyle.ST, false, new DERUTF8String("Test state"));

    return getCertificate(keyPair, certificateBuilder);
}
 
Example 28
Source Project: CapturePacket   Source File: BouncyCastleSecurityProviderTool.java    License: MIT License 5 votes vote down vote up
/**
 * Creates an X500Name based on the specified certificateInfo.
 *
 * @param certificateInfo information to populate the X500Name with
 * @return a new X500Name object for use as a subject or issuer
 */
private static X500Name createX500NameForCertificate(CertificateInfo certificateInfo) {
    X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);

    if (certificateInfo.getCommonName() != null) {
        x500NameBuilder.addRDN(BCStyle.CN, certificateInfo.getCommonName());
    }

    if (certificateInfo.getOrganization() != null) {
        x500NameBuilder.addRDN(BCStyle.O, certificateInfo.getOrganization());
    }

    if (certificateInfo.getOrganizationalUnit() != null) {
        x500NameBuilder.addRDN(BCStyle.OU, certificateInfo.getOrganizationalUnit());
    }

    if (certificateInfo.getEmail() != null) {
        x500NameBuilder.addRDN(BCStyle.E, certificateInfo.getEmail());
    }

    if (certificateInfo.getLocality() != null) {
        x500NameBuilder.addRDN(BCStyle.L, certificateInfo.getLocality());
    }

    if (certificateInfo.getState() != null) {
        x500NameBuilder.addRDN(BCStyle.ST, certificateInfo.getState());
    }

    if (certificateInfo.getCountryCode() != null) {
        x500NameBuilder.addRDN(BCStyle.C, certificateInfo.getCountryCode());
    }

    // TODO: Add more X.509 certificate fields as needed

    return x500NameBuilder.build();
}
 
Example 29
private static List<String> getCommonNames(X509Certificate certificate) {
    List<String> domains = new ArrayList<>();
    try {
        X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
        RDN[] rdns = x500name.getRDNs(BCStyle.CN);
        for (int i = 0; i < rdns.length; ++i) {
            domains.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[i].getFirst().getValue()));
        }
        return domains;
    } catch (CertificateEncodingException e) {
        return domains;
    }
}
 
Example 30
Source Project: xipki   Source File: DHSigStaticKeyCertPair.java    License: Apache License 2.0 5 votes vote down vote up
public DHSigStaticKeyCertPair(PrivateKey privateKey, X509Cert certificate) {
  this.privateKey = Args.notNull(privateKey, "privateKey");
  Args.notNull(certificate, "certificate");
  this.serialNumber = certificate.getSerialNumber();
  try {
    this.encodedIssuer = certificate.getIssuer().getEncoded();
    this.encodedSubject = certificate.getSubject().getEncoded();
  } catch (Exception ex) {
    throw new IllegalArgumentException("error encoding certificate", ex);
  }
  this.issuer = X500Name.getInstance(this.encodedIssuer);
  this.subject = X500Name.getInstance(this.encodedSubject);
}