Java Code Examples for org.bouncycastle.asn1.x509.SubjectPublicKeyInfo#getInstance()

The following examples show how to use org.bouncycastle.asn1.x509.SubjectPublicKeyInfo#getInstance() . 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: SSLKeyPairCerts.java    From vertx-tcp-eventbus-bridge with 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 2
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public void generateCA() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384k1");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(ecGenSpec, SecurityHelper.newRandom());
    KeyPair pair = generator.generateKeyPair();
    LocalDateTime startDate = LocalDate.now().atStartOfDay();

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, orgName.concat(" CA"));
    subject.addRDN(BCStyle.O, orgName);

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
            subject.build(),
            new BigInteger("0"),
            Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
            Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
            new X500Name("CN=ca"),
            SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    ca = builder.build(signer);
    caKey = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
}
 
Example 3
Source File: CA.java    From PacketProxy with Apache License 2.0 6 votes vote down vote up
private void initKeyStoreCA(InputStream input) throws Exception {
	this.keyStoreCA = KeyStore.getInstance("JKS");
	this.keyStoreCA.load(input, password);

	this.keyStoreCAPrivateKey = (PrivateKey) keyStoreCA.getKey(aliasRoot, password);

	/* RootのSubject(Issuer)の取り出し */
	Certificate caRootCert = keyStoreCA.getCertificate(aliasRoot);
	caRootHolder = new X509CertificateHolder(caRootCert.getEncoded());

	/* 有効期限の設定 */
	Date from = new Date();
	Calendar cal = Calendar.getInstance();
	cal.setTime(from);
	cal.add(Calendar.YEAR, 1);
	Date to = cal.getTime();

	/* Templateの設定 */
	templateIssuer = caRootHolder.getSubject();
	templateFrom = from;
	templateTo = to;
	templatePubKey = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
}
 
Example 4
Source File: OcspCertificateValidatorTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a certificate with a specific public key signed by the issuer key.
 *
 * @param dn        the subject DN
 * @param publicKey the subject public key
 * @param issuerDn  the issuer DN
 * @param issuerKey the issuer private key
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException,
        CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            new X500Name(issuerDn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

    X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example 5
Source File: CertificateUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber) {
    try {
        X500Name subjectDN = new X500Name("CN=" + subject);
        Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 10);
        Date validityEndDate = new Date(calendar.getTime().getTime());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded());

        X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate,
                validityEndDate, subjectDN, subPubKeyInfo);
        X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));

        return new JcaX509CertificateConverter().getCertificate(holder);
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v1Certificate.", e);
    }
}
 
Example 6
Source File: OpenSslPubUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Load an unencrypted OpenSSL public key from the stream. The encoding of
 * the public key may be PEM or DER.
 *
 * @param pkData BA to load the unencrypted public key from
 * @return The public key
 * @throws CryptoException
 *             Problem encountered while loading the public key
 * @throws IOException
 *             An I/O error occurred
 */
public static PublicKey load(byte[] pkData) throws CryptoException, IOException {

	// Check if stream is PEM encoded
	PemInfo pemInfo = PemUtil.decode(pkData);

	if (pemInfo != null) {
		// It is - get DER from PEM
		pkData = pemInfo.getContent();
	}

	try {
		// DER-encoded subjectPublicKeyInfo structure - the OpenSSL format
		SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pkData);
		return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
	} catch (Exception ex) {
		throw new CryptoException(res.getString("NoLoadOpenSslPublicKey.exception.message"), ex);
	}
}
 
Example 7
Source File: ProxyP11Slot.java    From xipki with Apache License 2.0 6 votes vote down vote up
private PublicKey getPublicKey(P11ObjectIdentifier objectId)
    throws P11UnknownEntityException, P11TokenException {
  ASN1Object req =
      new ProxyMessage.SlotIdAndObjectId(asn1SlotId, new ProxyMessage.ObjectIdentifier(objectId));
  byte[] resp = module.send(P11ProxyConstants.ACTION_GET_PUBLICKEY, req);
  if (resp == null) {
    return null;
  }

  SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfo.getInstance(resp);
  try {
    return KeyUtil.generatePublicKey(pkInfo);
  } catch (InvalidKeySpecException ex) {
    throw new P11TokenException("could not generate Public Key from SubjectPublicKeyInfo:"
        + ex.getMessage(), ex);
  }
}
 
Example 8
Source File: CertificateAutogenTask.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Path process(Path inputFile) throws IOException {
    if (signedDataGenerator != null) return inputFile;
    try {
        LogHelper.warning("You are using an auto-generated certificate (sign.enabled false). It is not good");
        LogHelper.warning("It is highly recommended that you use the correct certificate (sign.enabled true)");
        LogHelper.warning("You can use GenerateCertificateModule or your own certificate.");
        X500NameBuilder subject = new X500NameBuilder();
        subject.addRDN(BCStyle.CN, server.config.projectName.concat(" Autogenerated"));
        subject.addRDN(BCStyle.O, server.config.projectName);
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
        X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
                subject.build(),
                new BigInteger("0"),
                Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
                new X500Name("CN=ca"),
                SubjectPublicKeyInfo.getInstance(server.publicKey.getEncoded()));
        builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning));
        //builder.addExtension(Extension.keyUsage, false, new KeyUsage(1));
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
        ContentSigner signer = csBuilder.build(server.privateKey);
        bcCertificate = builder.build(signer);
        certificate = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(bcCertificate);
        ArrayList<Certificate> chain = new ArrayList<>();
        chain.add(certificate);
        signedDataGenerator = SignHelper.createSignedDataGenerator(server.privateKey, certificate, chain, "SHA256WITHECDSA");
    } catch (OperatorCreationException | CMSException | CertificateException e) {
        LogHelper.error(e);
    }
    return inputFile;
}
 
Example 9
Source File: KeyCodecTest.java    From UAF with Apache License 2.0 5 votes vote down vote up
@Test
public void pss() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, DataLengthException, CryptoException, InvalidKeyException, SignatureException, InvalidKeySpecException, IOException{
	KeyPair keyPair = KeyCodec.getRSAKeyPair();
	KeyPair keyPair2 = KeyCodec.getRSAKeyPair();
	
	PrivateKey privKey = keyPair.getPrivate();
	byte[] encodedPrivKey = privKey.getEncoded();
	logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey));

	PublicKey pubKey = keyPair.getPublic();
	byte[] encodedPubKey = pubKey.getEncoded();
	SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(encodedPubKey);
	ASN1Primitive primitive = spkInfo.parsePublicKey();
	
	PublicKey publicKey = KeyCodec.getRSAPublicKey(primitive.getEncoded());
	logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey));
	logger.info("pub format=" + pubKey.getFormat());
	logger.info("pub alg=" + pubKey.getAlgorithm());
	
	byte[] slt = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt
	
	byte[] signed = RSA.signPSS(privKey, slt);
	assertTrue(signed.length>0);
	RSA rsa = new RSA();
	Assert.assertTrue(rsa.verifyPSS(publicKey, slt, signed));
	byte[] slt2 = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776aa"); //a random salt  
	
	byte[] signed2 = RSA.signPSS(keyPair2.getPrivate(), slt2);
	Assert.assertFalse(rsa.verifyPSS(publicKey, slt2, signed2));
	Assert.assertFalse(rsa.verifyPSS(keyPair2.getPublic(), slt, signed));
}
 
Example 10
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source File: CtLogVerifyTest.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerify() throws Exception {
  Security.addProvider(new BouncyCastleProvider());
  byte[] keyBytes = read(pubkeyFile);

  SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(X509Util.toDerEncoded(keyBytes));
  byte[] keyId = HashAlgo.SHA256.hash(spki.getEncoded());
  System.out.println("keyId: " + Hex.encode(keyId));

  PublicKey key = KeyUtil.generatePublicKey(spki);
  X509Cert cert = X509Util.parseCert(read(certFile));
  X509Cert caCert = X509Util.parseCert(read(caCertFile));

  // CHECKSTYLE:SKIP
  byte[] issuerKeyHash = HashAlgo.SHA256.hash(caCert.getSubjectPublicKeyInfo().getEncoded());
  // CHECKSTYLE:SKIP
  byte[] preCertTbsCert = CtLog.getPreCertTbsCert(
                            cert.toBcCert().toASN1Structure().getTBSCertificate());

  byte[] extnValue = cert.getExtensionCoreValue(ObjectIdentifiers.Extn.id_SCTs);

  byte[] encodedScts = ASN1OctetString.getInstance(extnValue).getOctets();
  SignedCertificateTimestampList list = SignedCertificateTimestampList.getInstance(encodedScts);
  SerializedSCT sctList = list.getSctList();
  int size = sctList.size();
  Assert.assertEquals("SCT size", 2, size);

  SignedCertificateTimestamp sct = sctList.get(1);
  byte[] logId = sct.getLogId();
  Assert.assertEquals("logId", Hex.encodeUpper(keyId), Hex.encodeUpper(logId));

  Signature sig = Signature.getInstance("SHA256withECDSA");
  sig.initVerify(key);
  CtLog.update(sig, (byte) sct.getVersion(), sct.getTimestamp(),
      sct.getExtensions(), issuerKeyHash, preCertTbsCert);

  boolean sigValid = sig.verify(sct.getDigitallySigned().getSignature());
  Assert.assertEquals("signature valid", true, sigValid);
}
 
Example 12
Source File: SslConfigurer.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private X509Certificate createCert(KeyPair keyPair, String signatureAlgoritm, String domainName)
  throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateException, IOException {
  
  RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
  RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
  
  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgoritm);
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  
  ASN1InputStream publicKeyStream = new ASN1InputStream(rsaPublicKey.getEncoded());
  SubjectPublicKeyInfo pubKey = SubjectPublicKeyInfo.getInstance(publicKeyStream.readObject());
  publicKeyStream.close();
  
  X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())),
      new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
      new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)),
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      pubKey);
  
  RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus());
  ContentSigner contentSigner = sigGen.build(keyParams);
  
  X509CertificateHolder certificateHolder = v3CertBuilder.build(contentSigner);
  
  JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC");
  return certConverter.getCertificate(certificateHolder);
}
 
Example 13
Source File: OcspCertificateValidatorTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signed certificate with a specific keypair.
 *
 * @param dn      the DN
 * @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateCertificate(String dn, KeyPair keyPair) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException,
        InvalidKeyException, OperatorCreationException {
    PrivateKey privateKey = keyPair.getPrivate();
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(privateKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
            new X500Name(dn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

    // Set certificate extensions
    // (1) digitalSignature extension
    certBuilder.addExtension(X509Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement));

    // (2) extendedKeyUsage extension
    Vector<KeyPurposeId> ekUsages = new Vector<>();
    ekUsages.add(KeyPurposeId.id_kp_clientAuth);
    ekUsages.add(KeyPurposeId.id_kp_serverAuth);
    certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages));

    // Sign the certificate
    X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example 14
Source File: CertificateValidatorTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * will create a self-signed certificate
 *
 * @param dn the DN of the subject and issuer
 * @param startDate startdate of the validity of the created certificate
 * @param expiryDate expiration date of the created certificate
 * @param keyPair the keypair that is used to create the certificate
 * @return a X509-Certificate in version 3
 */
public X509Certificate createCertificate(String dn,
                                         Date startDate,
                                         Date expiryDate,
                                         KeyPair keyPair) {
    X500Name subjectDN = new X500Name(dn);
    X500Name issuerDN = new X500Name(dn);
    // @formatter:off
SubjectPublicKeyInfo subjPubKeyInfo = SubjectPublicKeyInfo.getInstance(
                                                    ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
// @formatter:on
    BigInteger serialNumber = new BigInteger(130, new SecureRandom());

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(issuerDN, serialNumber, startDate, expiryDate,
        subjectDN, subjPubKeyInfo);
    ContentSigner contentSigner = null;
    try {
        // @formatter:off
  contentSigner = new JcaContentSignerBuilder("SHA256withRSA")
                                                          .setProvider(BOUNCY_CASTLE_PROVIDER)
                                                          .build(keyPair.getPrivate());
  X509Certificate x509Certificate = new JcaX509CertificateConverter()
                                                          .setProvider(BOUNCY_CASTLE_PROVIDER)
                                                          .getCertificate(certGen.build(contentSigner));
  // @formatter:on
        return x509Certificate;
    } catch (CertificateException | OperatorCreationException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 15
Source File: X509Util.java    From logback-gelf with GNU Lesser General Public License v2.1 4 votes vote down vote up
X509Certificate build(final String commonName, final String... subjectAltName)
    throws IOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {

    final AlgorithmIdentifier sigAlgId =
        new DefaultSignatureAlgorithmIdentifierFinder().find(SIG_ALGORITHM);
    final AlgorithmIdentifier digAlgId =
        new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    final AsymmetricKeyParameter privateKeyAsymKeyParam =
        PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    final SubjectPublicKeyInfo subPubKeyInfo =
        SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final ContentSigner sigGen;

    final X500Name issuer = new X500Name(CA_NAME);
    final X500NameBuilder x500NameBuilder = new X500NameBuilder();
    if (commonName != null) {
        x500NameBuilder.addRDN(BCStyle.CN, commonName);
    }
    x500NameBuilder.addRDN(BCStyle.O, "snakeoil");
    final X500Name name = x500NameBuilder.build();

    final Date from = Date.valueOf(validFrom);
    final Date to = Date.valueOf(validTo);
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final X509v3CertificateBuilder v3CertGen =
        new X509v3CertificateBuilder(issuer, sn, from, to, name, subPubKeyInfo);

    if (caCertificate != null) {
        sigGen = new JcaContentSignerBuilder(SIG_ALGORITHM).build(caPrivateKey);

        final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCertificate));
    } else {
        sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(privateKeyAsymKeyParam);
    }

    if (subjectAltName != null) {
        final GeneralName[] generalNames = Arrays.stream(subjectAltName)
            .map(s -> new GeneralName(GeneralName.dNSName, s))
            .toArray(GeneralName[]::new);

        v3CertGen.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames).getEncoded());
    }

    final X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(certificateHolder);
}
 
Example 16
Source File: CtLogPublicKeyFinder.java    From xipki with Apache License 2.0 4 votes vote down vote up
public CtLogPublicKeyFinder(CtLogConf conf) throws IOException {
  String keydirName = conf.getKeydir();
  File[] keyFiles = null;
  if (keydirName != null && !keydirName.isEmpty()) {
    keydirName = IoUtil.expandFilepath(keydirName);
    keyFiles = new File(keydirName).listFiles(new FileFilter() {
      @Override
      public boolean accept(File pathname) {
        String name = pathname.getName();
        return pathname.isFile()
            && (name.endsWith(".pem") || name.endsWith(".der")
                || name.endsWith(".key") || name.endsWith(".publickey"));
      }
    });
  }

  if (keyFiles == null || keyFiles.length == 0) {
    this.logIds = null;
    this.publicKeys = null;
    this.withPublicKeys = false;
    return;
  }

  final int size = keyFiles.length;
  List<byte[]> logIdList = new ArrayList<>(size);
  List<PublicKey> publicKeyList = new ArrayList<>(size);

  for (File m : keyFiles) {
    byte[] keyBytes = IoUtil.read(m);
    keyBytes = X509Util.toDerEncoded(keyBytes);
    try {
      SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(keyBytes);
      byte[] logId = HashAlgo.SHA256.hash(spki.getEncoded());
      PublicKey key = KeyUtil.generatePublicKey(spki);

      logIdList.add(logId);
      publicKeyList.add(key);
      LOG.info("loaded CtLog public key {}", m.getName());
    } catch (IOException | InvalidKeySpecException ex) {
      LogUtil.error(LOG, ex, "could not load CtLog public key " + m.getName());
    }
  }

  this.logIds = logIdList.toArray(new byte[0][0]);
  this.publicKeys = publicKeyList.toArray(new PublicKey[0]);
  this.withPublicKeys = logIds != null && logIds.length > 0;

}
 
Example 17
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateCSRwithSan() throws NoSuchProviderException,
    NoSuchAlgorithmException, SCMSecurityException,
    OperatorCreationException, PKCSException {
  String clusterID = UUID.randomUUID().toString();
  String scmID = UUID.randomUUID().toString();
  String subject = "DN001";
  HDDSKeyGenerator keyGen =
      new HDDSKeyGenerator(securityConfig.getConfiguration());
  KeyPair keyPair = keyGen.generateKey();

  CertificateSignRequest.Builder builder =
      new CertificateSignRequest.Builder()
          .setSubject(subject)
          .setScmID(scmID)
          .setClusterID(clusterID)
          .setKey(keyPair)
          .setConfiguration(conf);

  // Multi-home
  builder.addIpAddress("192.168.1.1");
  builder.addIpAddress("192.168.2.1");
  builder.addServiceName("OzoneMarketingCluster003");

  builder.addDnsName("dn1.abc.com");

  PKCS10CertificationRequest csr = builder.build();

  // Check the Subject Name is in the expected format.
  String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(),
      subject, scmID, clusterID);
  Assert.assertEquals(csr.getSubject().toString(), dnName);

  // Verify the public key info match
  byte[] encoded = keyPair.getPublic().getEncoded();
  SubjectPublicKeyInfo subjectPublicKeyInfo =
      SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded));
  SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo();
  Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo);

  // Verify CSR with attribute for extensions
  Assert.assertEquals(1, csr.getAttributes().length);
  Extensions extensions = SecurityUtil.getPkcs9Extensions(csr);

  // Verify key usage extension
  Extension sanExt = extensions.getExtension(Extension.keyUsage);
  Assert.assertEquals(true, sanExt.isCritical());

  verifyServiceId(extensions);

  // Verify signature in CSR
  ContentVerifierProvider verifierProvider =
      new JcaContentVerifierProviderBuilder().setProvider(securityConfig
          .getProvider()).build(csr.getSubjectPublicKeyInfo());
  Assert.assertEquals(true, csr.isSignatureValid(verifierProvider));
}
 
Example 18
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateCSR() throws NoSuchProviderException,
    NoSuchAlgorithmException, SCMSecurityException,
    OperatorCreationException, PKCSException {
  String clusterID = UUID.randomUUID().toString();
  String scmID = UUID.randomUUID().toString();
  String subject = "DN001";
  HDDSKeyGenerator keyGen =
      new HDDSKeyGenerator(securityConfig.getConfiguration());
  KeyPair keyPair = keyGen.generateKey();

  CertificateSignRequest.Builder builder =
      new CertificateSignRequest.Builder()
          .setSubject(subject)
          .setScmID(scmID)
          .setClusterID(clusterID)
          .setKey(keyPair)
          .setConfiguration(conf);
  PKCS10CertificationRequest csr = builder.build();

  // Check the Subject Name is in the expected format.
  String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(),
      subject, scmID, clusterID);
  Assert.assertEquals(csr.getSubject().toString(), dnName);

  // Verify the public key info match
  byte[] encoded = keyPair.getPublic().getEncoded();
  SubjectPublicKeyInfo subjectPublicKeyInfo =
      SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded));
  SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo();
  Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo);

  // Verify CSR with attribute for extensions
  Assert.assertEquals(1, csr.getAttributes().length);
  Extensions extensions = SecurityUtil.getPkcs9Extensions(csr);

  // Verify key usage extension
  Extension keyUsageExt = extensions.getExtension(Extension.keyUsage);
  Assert.assertEquals(true, keyUsageExt.isCritical());


  // Verify San extension not set
  Assert.assertEquals(null,
      extensions.getExtension(Extension.subjectAlternativeName));

  // Verify signature in CSR
  ContentVerifierProvider verifierProvider =
      new JcaContentVerifierProviderBuilder().setProvider(securityConfig
          .getProvider()).build(csr.getSubjectPublicKeyInfo());
  Assert.assertEquals(true, csr.isSignatureValid(verifierProvider));
}
 
Example 19
Source File: verifyFido2RegistrationPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void verifyCryptographyOptions(CryptographyPolicyOptions cryptoOp, JsonObject clientJson,
        FIDO2AttestationObject attObject, Integer version) throws SKFEException {
    ArrayList<String> allowedRSASignatures = cryptoOp.getAllowedRSASignatures();
    ArrayList<String> allowedECSignatures = cryptoOp.getAllowedECSignatures();
    ArrayList<String> supportedCurves = cryptoOp.getSupportedEllipticCurves();
    ArrayList<String> allowedAttestationFormats = cryptoOp.getAllowedAttestationFormats();
    ArrayList<String> allowedAttestationTypes = cryptoOp.getAllowedAttestationTypes();

    //Verify attestation key
    ArrayList certificateChain = attObject.getAttStmt().getX5c();
    if(certificateChain != null){
        X509Certificate attestationCert = cryptoCommon.generateX509FromBytes((byte[]) certificateChain.get(0));

        if(attestationCert == null){
            throw new SKFEException("Failed to parse X509Certificate. Check logs for details");
        }
        PublicKey attestationKey = attestationCert.getPublicKey();
        String attestationAlgType = attestationKey.getAlgorithm();
        if(!attestationAlgType.equalsIgnoreCase("RSA") && !attestationAlgType.equalsIgnoreCase("EC")){
            throw new SKFEException("Unknown key algorithm (Attestation)");
        }
        if((allowedRSASignatures == null
                || !allowedRSASignatures.contains(skfsCommon.getPolicyAlgFromAlg(attestationCert.getSigAlgName())))
                && (allowedECSignatures == null
                || !allowedECSignatures.contains(skfsCommon.getPolicyAlgFromAlg(attestationCert.getSigAlgName())))){
            throw new SKFEException("Signature Algorithm not supported by policy (Attestation): " + attestationCert.getSigAlgName());
        }

        //Verify that the curve used by the attestation key is approved
        if(attestationAlgType.equalsIgnoreCase("EC")){
            byte[] enc = attestationKey.getEncoded();
            SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(enc));
            AlgorithmIdentifier algid = spki.getAlgorithm();
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) algid.getParameters();
            if(!supportedCurves.contains(skfsCommon.getPolicyCurveFromOID(oid))){
                throw new SKFEException("EC Curve not supported by policy (Attestation)");
            }
        }
    }

    //Verify signing key
    PublicKey signingKey = attObject.getAuthData().getAttCredData().getPublicKey();
    String signingAlgType = signingKey.getAlgorithm();
    if(!signingAlgType.equalsIgnoreCase("RSA") && !signingAlgType.equalsIgnoreCase("EC")){
        throw new SKFEException("Unknown attestation key algorithm (Signing)");
    }
    if((allowedRSASignatures == null
            || !allowedRSASignatures.contains(skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg())))
            && (allowedECSignatures == null
            ||!allowedECSignatures.contains(skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg())))){
        throw new SKFEException("Rejected key algorithm (Signing): " +
                skfsCommon.getPolicyAlgFromIANACOSEAlg(attObject.getAuthData().getAttCredData().getFko().getAlg()));
    }
    if(signingAlgType.equalsIgnoreCase("EC")){
        ECKeyObject eckey = (ECKeyObject) attObject.getAuthData().getAttCredData().getFko();
        if(!supportedCurves.contains(skfsCommon.getPolicyCurveFromFIDOECCCurveID(eckey.getCrv()))){
            throw new SKFEException("EC Curve not supported by policy (Signing)");
        }
    }

    //Verify allowed AttestationFormat
    if(!allowedAttestationFormats.contains(attObject.getAttFormat())){
        throw new SKFEException("Attestation format not supported by policy: " + attObject.getAttFormat());
    }

    //Verify allowed AttestationType
    if (!allowedAttestationTypes.contains(attObject.getAttStmt().getAttestationType())) {
        throw new SKFEException("Attestation type not supported by policy: " + attObject.getAttStmt().getAttestationType());
    }
}
 
Example 20
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher with MIT License 2 votes vote down vote up
/**
 * Creates the SubjectKeyIdentifier for a Bouncy Castle X590CertificateHolder.
 *
 * @param key public key to identify
 * @return SubjectKeyIdentifier for the specified key
 */
private static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key) {
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(key.getEncoded());

    return new BcX509ExtensionUtils().createSubjectKeyIdentifier(publicKeyInfo);
}