sun.security.x509.X509CertInfo Java Examples

The following examples show how to use sun.security.x509.X509CertInfo. 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: KeyStoreProviderTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateCertificate(final KeyPair pair, final String alias) throws GeneralSecurityException, IOException {
    final X509CertInfo info = new X509CertInfo();
    final X500Name name = new X500Name("dc=" + alias);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(256, RND)));
    info.set(X509CertInfo.SUBJECT, name);
    info.set(X509CertInfo.ISSUER, name);
    info.set(X509CertInfo.VALIDITY,
            new CertificateValidity(Date.from(Instant.now().minus(1, ChronoUnit.DAYS)),
                    Date.from(Instant.now().plus(730, ChronoUnit.DAYS))));
    info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
    info.set(X509CertInfo.ALGORITHM_ID,
            new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid)));

    final X509CertImpl cert = new X509CertImpl(info);
    cert.sign(pair.getPrivate(), AlgorithmId.sha256WithRSAEncryption_oid.toString());

    return cert;
}
 
Example #2
Source File: CertificateGeneration.java    From protect with MIT License 6 votes vote down vote up
/**
 * Issues an X.509v3 certificate signed by the given Certificate Authority
 * 
 * @param subjectDn
 * @param altNameIp        Subject alternative name IP address (may be null)
 * @param altNameHost      Subject alternative name hostname (may be null)
 * @param subjectPublicKey
 * @param validForDays
 * @param makeCa
 * @param issuerDn
 * @param caPrivateKey
 * @return
 */
public static X509Certificate generateCertificate(final String subjectDn, final String altNameIp,
		final String altNameHost, final PublicKey subjectPublicKey, final long validForDays, final boolean makeCa,
		final String issuerDn, final PrivateKey caPrivateKey) {

	try {

		// Look up algorithm based on CA private key
		final String signingAlgorithm = SigningUtil.getSigningAlgorithm(caPrivateKey);

		// Create Certificate Info
		final X509CertInfo certificateInfo = createCertificateInfo(subjectDn, altNameIp, altNameHost,
				subjectPublicKey, validForDays, makeCa, issuerDn, signingAlgorithm);

		// Create and sign the certificate
		final X509CertImpl certificate = new X509CertImpl(certificateInfo);

		// Sign certificate
		certificate.sign(caPrivateKey, signingAlgorithm);

		return certificate;

	} catch (GeneralSecurityException e) {
		throw new RuntimeException(e);
	}
}
 
Example #3
Source File: Keystores.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private static X509Certificate createSignedCertificate(final X509Certificate cetrificate, final X509Certificate issuerCertificate,
                                                       final PrivateKey issuerPrivateKey) {
    try {
        Principal issuer = issuerCertificate.getSubjectDN();
        String issuerSigAlg = issuerCertificate.getSigAlgName();

        byte[] inCertBytes = cetrificate.getTBSCertificate();
        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, (X500Name) issuer);

        //No need to add the BasicContraint for leaf cert
        if (!cetrificate.getSubjectDN().getName().equals("CN=TOP")) {
            CertificateExtensions exts = new CertificateExtensions();
            BasicConstraintsExtension bce = new BasicConstraintsExtension(true, -1);
            exts.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(false, bce.getExtensionValue()));
            info.set(X509CertInfo.EXTENSIONS, exts);
        }

        final X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);

        return outCert;
    } catch (final Exception ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #4
Source File: PKCS7.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #5
Source File: PKCS7.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #6
Source File: CoreSocketFactoryTest.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
private String createEphemeralCert(Duration shiftIntoPast)
    throws GeneralSecurityException, ExecutionException, IOException {
  Duration validFor = Duration.ofHours(1);
  ZonedDateTime notBefore = ZonedDateTime.now().minus(shiftIntoPast);
  ZonedDateTime notAfter = notBefore.plus(validFor);

  CertificateValidity interval =
      new CertificateValidity(Date.from(notBefore.toInstant()), Date.from(notAfter.toInstant()));

  X509CertInfo info = new X509CertInfo();
  info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
  info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(1));
  info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get("SHA1withRSA")));
  info.set(X509CertInfo.SUBJECT, new X500Name("C = US, O = Google\\, Inc, CN=temporary-subject"));
  info.set(X509CertInfo.KEY, new CertificateX509Key(Futures.getDone(clientKeyPair).getPublic()));
  info.set(X509CertInfo.VALIDITY, interval);
  info.set(
      X509CertInfo.ISSUER,
      new X500Name("C = US, O = Google\\, Inc, CN=Google Cloud SQL Signing CA foo:baz"));

  KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec keySpec =
      new PKCS8EncodedKeySpec(decodeBase64StripWhitespace(TestKeys.SIGNING_CA_PRIVATE_KEY));
  PrivateKey signingKey = keyFactory.generatePrivate(keySpec);

  X509CertImpl cert = new X509CertImpl(info);
  cert.sign(signingKey, "SHA1withRSA");

  StringBuilder sb = new StringBuilder();
  sb.append("-----BEGIN CERTIFICATE-----\n");
  sb.append(Base64.getEncoder().encodeToString(cert.getEncoded()).replaceAll("(.{64})", "$1\n"));
  sb.append("\n");
  sb.append("-----END CERTIFICATE-----\n");

  return sb.toString();
}
 
Example #7
Source File: PKCS7.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #8
Source File: PKCS7.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #9
Source File: PKCS7.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #10
Source File: PKCS7.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #11
Source File: PKCS7.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #12
Source File: PKCS7.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #13
Source File: PKCS7.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #14
Source File: CertificateGeneration.java    From protect with MIT License 5 votes vote down vote up
/**
 * Creates a certificate from an X509Certificate info and a raw signature
 * 
 * @param toBeSignedCertificateInfo
 * @param certificateSigningAlgorithm
 * @param signature
 * @return
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws SignatureException
 */
public static final X509Certificate createCertificateFromTbsAndSignature(
		final X509CertInfo toBeSignedCertificateInfo, final String certificateSigningAlgorithm,
		final byte[] signature) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
		NoSuchProviderException, SignatureException {

	try (DerOutputStream out = new DerOutputStream(); DerOutputStream tmp = new DerOutputStream();) {

		// Append the certificate information
		toBeSignedCertificateInfo.encode(tmp);

		// Append the signature algorithm
		final AlgorithmId algId = AlgorithmId.get(certificateSigningAlgorithm);
		algId.encode(tmp);

		// Append the signature
		tmp.putBitString(signature);

		// Wrap the signed data in a SEQUENCE { data, algorithm, sig }
		out.write(DerValue.tag_Sequence, tmp);
		byte[] signedCert = out.toByteArray();

		// Create a certificate
		return new X509CertImpl(signedCert);

	} catch (IOException e) {
		throw new CertificateEncodingException(e.toString());
	}
}
 
Example #15
Source File: PKCS7.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #16
Source File: PKCS7.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #17
Source File: RsaSigningClient.java    From protect with MIT License 5 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException,
		IOException, CertificateException, NoSuchProviderException {

	// Key generation
	KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
	generator.initialize(1024);
	KeyPair rsaKeyPair = generator.generateKeyPair();
	RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) rsaKeyPair.getPrivate();
	RSAPublicKey rsaPublicKey = (RSAPublicKey) rsaKeyPair.getPublic();

	// Generate certificate without a signature
	final X509CertInfo certInfo = createCertificateInfo("CN=test", null, null, rsaKeyPair.getPublic(), 365, true,
			"CN=test");
	final X509CertImpl certificate = new X509CertImpl(certInfo);
	final byte[] toBeSigned = certificate.getTBSCertificate();

	// Manually sign it
	final BigInteger toBeSignedRaw = EMSA_PKCS1_V1_5_ENCODE(toBeSigned, rsaPublicKey.getModulus());
	final byte[] signature = Exponentiation
			.modPow(toBeSignedRaw, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus()).toByteArray();

	// Create the certificate passing in the signature
	final X509Certificate cert = createCertificateFromTbsAndSignature(certInfo, signature);

	System.out.println(cert);
	cert.verify(rsaKeyPair.getPublic());
	System.out.println("Certificate is valid!");
}
 
Example #18
Source File: RsaSigningClient.java    From protect with MIT License 5 votes vote down vote up
static final X509Certificate createCertificateFromTbsAndSignature(X509CertInfo info, final byte[] signature)
		throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
		SignatureException {

	try (DerOutputStream out = new DerOutputStream(); DerOutputStream tmp = new DerOutputStream();) {

		// Append the certificate information
		info.encode(tmp);

		// Append the signature algorithm
		final AlgorithmId algId = AlgorithmId.get(CERTIFICATE_SIGNING_ALGORITHM);
		algId.encode(tmp);

		// Append the signature
		tmp.putBitString(signature);

		// Wrap the signed data in a SEQUENCE { data, algorithm, sig }
		out.write(DerValue.tag_Sequence, tmp);
		byte[] signedCert = out.toByteArray();

		// Create a certificate
		return new X509CertImpl(signedCert);

	} catch (IOException e) {
		throw new CertificateEncodingException(e.toString());
	}
}
 
Example #19
Source File: PKCS7.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #20
Source File: PKCS7.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #21
Source File: PKCS7.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #22
Source File: PKCS7.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;

    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // must extract the original encoded form of DN for
            // subsequent name comparison checks (converting to a
            // String and back to an encoded DN could cause the
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert =
                    new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal)
                    tbsCert.get(X509CertInfo.ISSUER + "." +
                                X509CertInfo.DN_NAME);
            } catch (Exception e) {
                // error generating X500Name object from the cert's
                // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
 
Example #23
Source File: JavaKeyStoreUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws CertificateException, IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    X509CertInfo certInfo = new X509CertInfo();
    // Serial number and version
    certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, new SecureRandom())));
    certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));

    // Subject & Issuer
    X500Name owner = new X500Name(DN_NAME);
    certInfo.set(X509CertInfo.SUBJECT, owner);
    certInfo.set(X509CertInfo.ISSUER, owner);

    // Key and algorithm
    certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
    AlgorithmId algorithm = new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid);
    certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithm));

    // Validity
    Date validFrom = new Date();
    Date validTo = new Date(validFrom.getTime() + 50L * 365L * 24L * 60L * 60L * 1000L); //50 years
    CertificateValidity validity = new CertificateValidity(validFrom, validTo);
    certInfo.set(X509CertInfo.VALIDITY, validity);
    
    GeneralNameInterface dnsName = new DNSName("baeldung.com");
    DerOutputStream dnsNameOutputStream = new DerOutputStream();
    dnsName.encode(dnsNameOutputStream);
    
    GeneralNameInterface ipAddress = new IPAddressName("127.0.0.1");
    DerOutputStream ipAddressOutputStream = new DerOutputStream();
    ipAddress.encode(ipAddressOutputStream);
    
    GeneralNames generalNames = new GeneralNames();
    generalNames.add(new GeneralName(dnsName));
    generalNames.add(new GeneralName(ipAddress));
    
    CertificateExtensions ext = new CertificateExtensions();
    ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(generalNames));

    certInfo.set(X509CertInfo.EXTENSIONS, ext);        

    // Create certificate and sign it
    X509CertImpl cert = new X509CertImpl(certInfo);
    cert.sign(keyPair.getPrivate(), SHA1WITHRSA);

    // Since the SHA1withRSA provider may have a different algorithm ID to what we think it should be,
    // we need to reset the algorithm ID, and resign the certificate
    AlgorithmId actualAlgorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
    certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, actualAlgorithm);
    X509CertImpl newCert = new X509CertImpl(certInfo);
    newCert.sign(keyPair.getPrivate(), SHA1WITHRSA);

    return newCert;
}
 
Example #24
Source File: F.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public F() {
    // jdk internal API
    cert = new X509CertInfo();
}
 
Example #25
Source File: CertificateGeneration.java    From protect with MIT License 4 votes vote down vote up
public static X509CertInfo createCertificateInfo(final String subjectDn, final String altNameIp,
		final String altNameHost, final PublicKey subjectPublicKey, final long validForDays, final boolean makeCa,
		final String issuerDn, final String certificateSigningAlgorithm) {

	try {

		// Look up algorithm based on CA private key
		final AlgorithmId algorithmId = AlgorithmId.get(certificateSigningAlgorithm);

		// Define validity period
		final Date notBefore = new Date(new Date().getTime() - 300); // 5 minutes prior to avoid clock skew issues
		final Date notAfter = new Date(notBefore.getTime() + (validForDays * 24 * 3600 * 1000));
		final CertificateValidity validity = new CertificateValidity(notBefore, notAfter);

		// Random serial number
		final BigInteger serialNumber = RandomNumberGenerator.generateRandomInteger(128);

		// Define information within certificate
		final X509CertInfo certificateInfo = new X509CertInfo();
		certificateInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
		certificateInfo.set(X509CertInfo.VALIDITY, validity);
		certificateInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(serialNumber));
		certificateInfo.set(X509CertInfo.SUBJECT, new X500Name(subjectDn));
		certificateInfo.set(X509CertInfo.ISSUER, new X500Name(issuerDn));
		certificateInfo.set(X509CertInfo.KEY, new CertificateX509Key(subjectPublicKey));
		certificateInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithmId));

		// Process extensions
		final CertificateExtensions extensions = new CertificateExtensions();

		// Make the issued certificate a sub-CA of this one (or self-signed)
		final BasicConstraintsExtension bce = new BasicConstraintsExtension(makeCa, 0);
		extensions.set(BasicConstraintsExtension.NAME,
				new BasicConstraintsExtension(true, bce.getExtensionValue()));

		// Add a subject alternative name (if not null)
		if (altNameIp != null) {
			final GeneralNames generalNames = new GeneralNames();
			generalNames.add(new GeneralName(new IPAddressName(altNameIp)));
			generalNames.add(new GeneralName(new DNSName(altNameHost)));
			final SubjectAlternativeNameExtension san = new SubjectAlternativeNameExtension(false, generalNames);
			extensions.set(SubjectAlternativeNameExtension.NAME, san);
		}

		certificateInfo.set(X509CertInfo.EXTENSIONS, extensions);

		return certificateInfo;

	} catch (GeneralSecurityException | IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #26
Source File: RsaCertificateAuthorityClient.java    From protect with MIT License 4 votes vote down vote up
public void issuerCertificate() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException,
		IOException, ResourceUnavailableException, BelowThresholdException, NoSuchAlgorithmException,
		CertificateException, InvalidKeySpecException, InvalidKeyException, NoSuchProviderException,
		SignatureException, BadArgumentException {

	// Test most common configuration

	// Use openSSL to verify it

	// Print status
	System.out.println("-----------------------------------------------------------");
	System.out.println("Issing certificate using threshold RSA secret: " + this.secretName);
	System.out.print("  Reading end-entity public key from file: " + this.publicKeyFile + "... ");
	final PublicKey entityPublicKey = (PublicKey) Pem.loadKeyFromFile(this.publicKeyFile);
	System.out.println("done.");

	System.out.print("  Loading CA certificate from file: " + this.publicKeyFile + "... ");
	final X509Certificate caCertificate = Pem.loadCertificateFromFile(caFile);
	System.out.println("done.");

	System.out.print("  Creating a To-Be-Signed Certificate for: " + this.subjectDn + "... ");
	final X509CertInfo certificateInfo = CertificateGeneration.createCertificateInfo(subjectDn, null, null,
			entityPublicKey, 365, false, caCertificate.getSubjectDN().getName(), CERTIFICATE_SIGNING_ALGORITHM);
	final X509CertImpl certificate = new X509CertImpl(certificateInfo);
	final byte[] toBeSigned = certificate.getTBSCertificate();
	final BigInteger toBeSignedRaw = EMSA_PKCS1_V1_5_ENCODE(toBeSigned,
			((RSAPublicKey) caCertificate.getPublicKey()).getModulus());
	System.out.println("done.");

	// Get public key and current epoch from the server
	System.out.print("  Performing threshold signing of certificate using: " + this.secretName + "... ");
	final BigInteger signatureResult = this.signMessage(toBeSignedRaw);
	System.out.println("done.");
	System.out.println("Signature result obtained: " + signatureResult);
	System.out.println();

	System.out.print("  Creating certificate using signature... ");
	final byte[] signature = signatureResult.toByteArray();
	final X509Certificate cert = CertificateGeneration.createCertificateFromTbsAndSignature(certificateInfo,
			CERTIFICATE_SIGNING_ALGORITHM, signature);
	cert.verify(caCertificate.getPublicKey());
	System.out.println("  done. Certificate is valid!");

	// Write plaintext to output file
	System.out.print("Writing signed certificate to file: " + this.certificateOutputFile + "... ");
	Pem.storeCertificateToFile(cert, this.certificateOutputFile);
	System.out.println(" done.");
	System.out.println();

	System.out.println("Operation complete. Certificate now ready for use.");
}
 
Example #27
Source File: RsaSigningClient.java    From protect with MIT License 4 votes vote down vote up
protected static X509CertInfo createCertificateInfo(final String subjectDn, final String altNameIp,
		final String altNameHost, final PublicKey subjectPublicKey, final long validForDays, final boolean makeCa,
		final String issuerDn) {

	try {

		// Look up algorithm based on CA private key
		final AlgorithmId algorithmId = AlgorithmId.get(CERTIFICATE_SIGNING_ALGORITHM);

		// Define validity period
		final Date notBefore = new Date(new Date().getTime() - 300); // 5 minutes prior to avoid clock skew issues
		final Date notAfter = new Date(notBefore.getTime() + (validForDays * 24 * 3600 * 1000));
		final CertificateValidity validity = new CertificateValidity(notBefore, notAfter);

		// Random serial number
		final BigInteger serialNumber = RandomNumberGenerator.generateRandomInteger(128);

		// Define information within certificate
		final X509CertInfo certificateInfo = new X509CertInfo();
		certificateInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
		certificateInfo.set(X509CertInfo.VALIDITY, validity);
		certificateInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(serialNumber));
		certificateInfo.set(X509CertInfo.SUBJECT, new X500Name(subjectDn));
		certificateInfo.set(X509CertInfo.ISSUER, new X500Name(issuerDn));
		certificateInfo.set(X509CertInfo.KEY, new CertificateX509Key(subjectPublicKey));
		certificateInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithmId));

		// Process extensions
		final CertificateExtensions extensions = new CertificateExtensions();

		// Make the issued certificate a sub-CA of this one (or self-signed)
		final BasicConstraintsExtension bce = new BasicConstraintsExtension(makeCa, 0);
		extensions.set(BasicConstraintsExtension.NAME,
				new BasicConstraintsExtension(true, bce.getExtensionValue()));

		// Add a subject alternative name (if not null)
		if (altNameIp != null) {
			final GeneralNames generalNames = new GeneralNames();
			generalNames.add(new GeneralName(new IPAddressName(altNameIp)));
			generalNames.add(new GeneralName(new DNSName(altNameHost)));
			final SubjectAlternativeNameExtension san = new SubjectAlternativeNameExtension(false, generalNames);
			extensions.set(SubjectAlternativeNameExtension.NAME, san);
		}

		certificateInfo.set(X509CertInfo.EXTENSIONS, extensions);

		return certificateInfo;

	} catch (GeneralSecurityException | IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #28
Source File: SM2X509CertImpl.java    From julongchain with Apache License 2.0 4 votes vote down vote up
public SM2X509CertImpl(X509CertInfo info) {
    super(info);
}