java.security.cert.X509Certificate Java Examples

The following examples show how to use java.security.cert.X509Certificate. 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: TPMAttestationStatementValidator.java    From webauthn4j with Apache License 2.0 7 votes vote down vote up
private void validateX5c(TPMAttestationStatement attestationStatement, TPMSAttest certInfo, AuthenticatorData<RegistrationExtensionAuthenticatorOutput<?>> authenticatorData) {
    X509Certificate aikCert = attestationStatement.getX5c().getEndEntityAttestationCertificate().getCertificate();

    /// Verify the sig is a valid signature over certInfo using the attestation public key in aikCert with the algorithm specified in alg.
    String jcaName = getJcaName(attestationStatement.getAlg());
    Signature certInfoSignature = SignatureUtil.createSignature(jcaName);
    try {
        certInfoSignature.initVerify(aikCert.getPublicKey());
        certInfoSignature.update(certInfo.getBytes());
        if (!certInfoSignature.verify(attestationStatement.getSig())) {
            throw new BadAttestationStatementException("hash of certInfo doesn't match with sig.");
        }
    } catch (SignatureException | InvalidKeyException e) {
        throw new BadAttestationStatementException("Failed to validate the signature.", e);
    }

    /// Verify that aikCert meets the requirements in §8.3.1 TPM Attestation Statement Certificate Requirements.
    validateAikCert(aikCert);

    /// If aikCert contains an extension with OID 1 3 6 1 4 1 45724 1 1 4 (id-fido-gen-ce-aaguid) verify that the value of this extension matches the aaguid in authenticatorData.
    byte[] aaguidBytes = aikCert.getExtensionValue(ID_FIDO_GEN_CE_AAGUID);
    if (aaguidBytes != null && !Objects.equals(new AAGUID(aaguidBytes), authenticatorData.getAttestedCredentialData().getAaguid())) {
        throw new BadAttestationStatementException("AAGUID in aikCert doesn't match with that in authenticatorData");
    }
}
 
Example #2
Source File: AbstractConsultationServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
protected D obtainCompleteness(X509Certificate certificate, PrivateKey privateKey, C consultRequest) throws TechnicalConnectorException {
   if (certificate != null && privateKey != null) {
      GenericRequest request = ServiceFactory.getTSConsultService(certificate, privateKey);
      request.setPayload(consultRequest);

      try {
         return be.ehealth.technicalconnector.ws.ServiceFactory.getGenericWsSender().send(request).asObject(this.clazzD);
      } catch (SOAPException var6) {
         throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, new Object[]{var6.getMessage(), var6});
      }
   } else {
      TechnicalConnectorExceptionValues errorValue = TechnicalConnectorExceptionValues.SECURITY_NO_CERTIFICATE;
      LOG.debug("\t## " + errorValue.getMessage());
      throw new TechnicalConnectorException(errorValue, (Throwable)null, new Object[0]);
   }
}
 
Example #3
Source File: TrustOnFirstUseManagerTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddFingerPrintFailedToWrite() throws CertificateException, IOException {

    Path notWritable = Paths.get(tmpDir.getRoot().getPath(), "notWritable");

    Files.createFile(notWritable);
    Files.setPosixFilePermissions(notWritable, PosixFilePermissions.fromString("r--------"));

    trustManager = new TrustOnFirstUseManager(notWritable);

    X509Certificate certificate = mock(X509Certificate.class);
    when(certificate.getEncoded()).thenReturn("certificate".getBytes(UTF_8));
    X500Principal cn = new X500Principal("CN=localhost");
    when(certificate.getSubjectX500Principal()).thenReturn(cn);

    try {
        trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "s");
        trustManager.checkClientTrusted(new X509Certificate[]{certificate}, "s");

        failBecauseExceptionWasNotThrown(CertificateException.class);
    } catch (Exception ex) {
        assertThat(ex).isInstanceOf(CertificateException.class);
    }
}
 
Example #4
Source File: KeyDepotManagerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private EncryptionToken getEtkBasedOnX509(X509Certificate cert) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(cert);
   IdentifierType identifierType = parser.getIdentifier();
   String identifierValue = parser.getId();
   String application = parser.getApplication();
   if (identifierType != null && !StringUtils.isEmpty(identifierValue) && StringUtils.isNumeric(identifierValue)) {
      try {
         return this.getEtk(identifierType, Long.parseLong(identifierValue), application);
      } catch (NumberFormatException var7) {
         LOG.error(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND.getMessage());
         throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND, var7, new Object[0]);
      }
   } else {
      LOG.error(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND.getMessage());
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_ETK_NOTFOUND, new Object[0]);
   }
}
 
Example #5
Source File: ForwardBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the builder with the input parameters.
 *
 * @param params the parameter set used to build a certification path
 */
ForwardBuilder(BuilderParams buildParams, boolean searchAllCertStores) {
    super(buildParams);

    // populate sets of trusted certificates and subject DNs
    trustAnchors = buildParams.trustAnchors();
    trustedCerts = new HashSet<X509Certificate>(trustAnchors.size());
    trustedSubjectDNs = new HashSet<X500Principal>(trustAnchors.size());
    for (TrustAnchor anchor : trustAnchors) {
        X509Certificate trustedCert = anchor.getTrustedCert();
        if (trustedCert != null) {
            trustedCerts.add(trustedCert);
            trustedSubjectDNs.add(trustedCert.getSubjectX500Principal());
        } else {
            trustedSubjectDNs.add(anchor.getCA());
        }
    }
    this.searchAllCertStores = searchAllCertStores;
}
 
Example #6
Source File: ForwardBuilder.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the builder with the input parameters.
 *
 * @param params the parameter set used to build a certification path
 */
ForwardBuilder(BuilderParams buildParams, boolean searchAllCertStores) {
    super(buildParams);

    // populate sets of trusted certificates and subject DNs
    trustAnchors = buildParams.trustAnchors();
    trustedCerts = new HashSet<X509Certificate>(trustAnchors.size());
    trustedSubjectDNs = new HashSet<X500Principal>(trustAnchors.size());
    for (TrustAnchor anchor : trustAnchors) {
        X509Certificate trustedCert = anchor.getTrustedCert();
        if (trustedCert != null) {
            trustedCerts.add(trustedCert);
            trustedSubjectDNs.add(trustedCert.getSubjectX500Principal());
        } else {
            trustedSubjectDNs.add(anchor.getCA());
        }
    }
    this.searchAllCertStores = searchAllCertStores;
}
 
Example #7
Source File: GenericWsSenderImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sendCertificateSecured(String url, String payload, X509Certificate certificate, PrivateKey privateKey, String soapAction) throws TechnicalConnectorException {
   GenericRequest request = new GenericRequest();
   request.setPayload(payload);
   request.setEndpoint(url);
   if (soapAction != null && soapAction.isEmpty()) {
      request.setSoapAction(soapAction);
   }

   request.setHandlerChain((new HandlerChain()).register(HandlerPosition.SECURITY, new CertificateCallback(certificate, privateKey)).register(HandlerPosition.SECURITY, new SoapActionHandler()));
   request.setDefaultHandlerChain();

   try {
      return this.send(request).asString();
   } catch (SOAPException var8) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, var8, new Object[]{var8.getMessage()});
   }
}
 
Example #8
Source File: CertificateFactory.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public CertPath engineGenerateCertPath(
    List certificates)
    throws CertificateException
{
    Iterator iter = certificates.iterator();
    Object obj;
    while (iter.hasNext())
    {
        obj = iter.next();
        if (obj != null)
        {
            if (!(obj instanceof X509Certificate))
            {
                throw new CertificateException("list contains non X509Certificate object while creating CertPath\n" + obj.toString());
            }
        }
    }
    return new PKIXCertPath(certificates);
}
 
Example #9
Source File: TrustOnFirstUseManagerTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void testCertificateNotValidForRecognisedAddress() throws CertificateException, IOException {
    testAddThumbPrintToKnownHostsList();

    when(certificate.getEncoded()).thenReturn("ADifferentCertificate".getBytes(UTF_8));
    X500Principal cn = new X500Principal("CN=localhost");
    when(certificate.getSubjectX500Principal()).thenReturn(cn);

    try {
        trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "str");
        failBecauseExceptionWasNotThrown(IOException.class);
    } catch (Exception ex) {
        assertThat(ex)
            .isInstanceOf(CertificateException.class)
            .hasMessageContaining("This address has been associated with a different certificate");
    }

    verify(certificate, times(3)).getEncoded();
    verify(certificate, times(3)).getSubjectX500Principal();

}
 
Example #10
Source File: PKCS7.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the X.509 certificate listed in this PKCS7 block
 * which has a matching serial number and Issuer name, or
 * null if one is not found.
 *
 * @param serial the serial number of the certificate to retrieve.
 * @param issuerName the Distinguished Name of the Issuer.
 */
public X509Certificate getCertificate(BigInteger serial, X500Name issuerName) {
    if (certificates != null) {
        if (certIssuerNames == null)
            populateCertIssuerNames();
        for (int i = 0; i < certificates.length; i++) {
            X509Certificate cert = certificates[i];
            BigInteger thisSerial = cert.getSerialNumber();
            if (serial.equals(thisSerial)
                && issuerName.equals(certIssuerNames[i]))
            {
                return cert;
            }
        }
    }
    return null;
}
 
Example #11
Source File: SiaUtils.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static Optional<X509Certificate> readCertificateFile(Path root, AthenzIdentity service) {
    try {
        Path certificateFile = getCertificateFile(root, service);
        if (Files.notExists(certificateFile)) return Optional.empty();
        return Optional.of(X509CertificateUtils.fromPem(new String(Files.readAllBytes(certificateFile))));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #12
Source File: TimestampedSigner.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generates a PKCS #7 signed data message that includes a signature
 * timestamp.
 * This method is used when a signature has already been generated.
 * The signature, a signature timestamp, the signer's certificate chain,
 * and optionally the content that was signed, are packaged into a PKCS #7
 * signed data message.
 *
 * @param params The non-null input parameters.
 * @param omitContent true if the content should be omitted from the
 *        signed data message. Otherwise the content is included.
 * @param applyTimestamp true if the signature should be timestamped.
 *        Otherwise timestamping is not performed.
 * @return A PKCS #7 signed data message including a signature timestamp.
 * @throws NoSuchAlgorithmException The exception is thrown if the signature
 *         algorithm is unrecognised.
 * @throws CertificateException The exception is thrown if an error occurs
 *         while processing the signer's certificate or the TSA's
 *         certificate.
 * @throws IOException The exception is thrown if an error occurs while
 *         generating the signature timestamp or while generating the signed
 *         data message.
 * @throws NullPointerException The exception is thrown if parameters is
 *         null.
 */
public byte[] generateSignedData(ContentSignerParameters params,
    boolean omitContent, boolean applyTimestamp)
        throws NoSuchAlgorithmException, CertificateException, IOException {

    if (params == null) {
        throw new NullPointerException();
    }

    // Parse the signature algorithm to extract the digest
    // algorithm. The expected format is:
    //     "<digest>with<encryption>"
    // or  "<digest>with<encryption>and<mgf>"
    String signatureAlgorithm = params.getSignatureAlgorithm();

    X509Certificate[] signerChain = params.getSignerCertificateChain();
    byte[] signature = params.getSignature();

    // Include or exclude content
    byte[] content = (omitContent == true) ? null : params.getContent();

    URI tsaURI = null;
    if (applyTimestamp) {
        tsaURI = params.getTimestampingAuthority();
        if (tsaURI == null) {
            // Examine TSA cert
            tsaURI = getTimestampingURI(
                params.getTimestampingAuthorityCertificate());
            if (tsaURI == null) {
                throw new CertificateException(
                    "Subject Information Access extension not found");
            }
        }
    }
    return PKCS7.generateSignedData(signature, signerChain, content,
                                    params.getSignatureAlgorithm(), tsaURI,
                                    params.getTSAPolicyID(),
                                    params.getTSADigestAlg());
}
 
Example #13
Source File: XMLX509IssuerSerial.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor XMLX509IssuerSerial
 *
 * @param doc
 * @param x509certificate
 */
public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
    this(
        doc,
        x509certificate.getIssuerX500Principal().getName(),
        x509certificate.getSerialNumber()
    );
}
 
Example #14
Source File: StartDateTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example #15
Source File: EndEntityExtensionCheck.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void check(Certificate cert,
                  Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {
    X509Certificate currCert = (X509Certificate)cert;
    // check that this is an EE cert
    if (currCert.getBasicConstraints() == -1) {
        if (unresolvedCritExts != null &&
                !unresolvedCritExts.isEmpty()) {
            unresolvedCritExts.remove("1.2.3.4");
        }
    }
}
 
Example #16
Source File: Secmod.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] getDigest(X509Certificate cert, String algorithm) {
    try {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        return md.digest(cert.getEncoded());
    } catch (GeneralSecurityException e) {
        throw new ProviderException(e);
    }
}
 
Example #17
Source File: RetrievalMethodResolver.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves a x509Certificate from the given information
 * @param e
 * @param baseURI
 * @param storage
 * @return
 * @throws KeyResolverException
 */
private static X509Certificate resolveCertificate(
    Element e, String baseURI, StorageResolver storage
) throws KeyResolverException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"
            + e.getLocalName() + " Element");
    }
    // An element has been provided
    if (e != null) {
        return KeyResolver.getX509Certificate(e, baseURI, storage);
    }
    return null;
}
 
Example #18
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns CRLs described in a X509Certificate's CRLDistributionPoints
 * Extension. Only those containing a general name of type URI are read.
 */
public static List<CRL> readCRLsFromCert(X509Certificate cert)
        throws Exception {
    List<CRL> crls = new ArrayList<>();
    CRLDistributionPointsExtension ext =
            X509CertImpl.toImpl(cert).getCRLDistributionPointsExtension();
    if (ext == null) return crls;
    List<DistributionPoint> distPoints =
            ext.get(CRLDistributionPointsExtension.POINTS);
    for (DistributionPoint o: distPoints) {
        GeneralNames names = o.getFullName();
        if (names != null) {
            for (GeneralName name: names.names()) {
                if (name.getType() == GeneralNameInterface.NAME_URI) {
                    URIName uriName = (URIName)name.getName();
                    for (CRL crl: loadCRLs(uriName.getName())) {
                        if (crl instanceof X509CRL) {
                            crls.add((X509CRL)crl);
                        }
                    }
                    break;  // Different name should point to same CRL
                }
            }
        }
    }
    return crls;
}
 
Example #19
Source File: PrivateKeyResolver.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?");

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {

            Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                XMLX509SubjectName certSN =
                    new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert);

                if (certSN.equals(x509SubjectName)) {
                    log.log(java.util.logging.Level.FINE, "match !!! ");

                    try {
                        Key key = keyStore.getKey(alias, password);
                        if (key instanceof PrivateKey) {
                            return (PrivateKey) key;
                        }
                    } catch (Exception e) {
                        log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
                        // Keep searching
                    }
                }
            }
        }
    }

    return null;
}
 
Example #20
Source File: DefaultCacheImpl.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public boolean contains(List<? extends X509Certificate> key) {
   synchronized(map) {
     EntryWithAge entry = map.get(key);
     if ((entry != null)
         && (timeSource.currentTimeMillis() < entry.expireMillis)) {
       return true;
     }
     return false;
   }
}
 
Example #21
Source File: BuildEEBasicConstraints.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example #22
Source File: CertReplace.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param args {cacerts keystore, cert chain}
 */
public static void main(String[] args) throws Exception {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(args[0]), "changeit".toCharArray());
    Validator v = Validator.getInstance
        (Validator.TYPE_PKIX, Validator.VAR_GENERIC, ks);
    X509Certificate[] chain = createPath(args[1]);
    System.out.println("Chain: ");
    for (X509Certificate c: v.validate(chain)) {
        System.out.println("   " + c.getSubjectX500Principal() +
                " issued by " + c.getIssuerX500Principal());
    }
}
 
Example #23
Source File: X509SubjectNameResolver.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method engineResolvePublicKey
 *
 * @param element
 * @param BaseURI
 * @param storage
 * @return null if no {@link PublicKey} could be obtained
 * @throws KeyResolverException
 */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {

    X509Certificate cert =
        this.engineLookupResolveX509Certificate(element, baseURI, storage);

    if (cert != null) {
        return cert.getPublicKey();
    }

    return null;
}
 
Example #24
Source File: SFTrustManagerIT.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Read certificates from a file.
 *
 * @param filename file name under resources directory
 * @return an array of X509Certificate
 * @throws Throwable raise if any error occurs
 */
private List<X509Certificate> getX509CertificatesFromFile(String filename) throws Throwable
{
  CertificateFactory fact = CertificateFactory.getInstance("X.509");
  List<X509Certificate> certList = new ArrayList<>();
  for (Certificate cert : fact.generateCertificates(getFile(filename)))
  {
    certList.add((X509Certificate) cert);
  }
  return certList;
}
 
Example #25
Source File: XMLX509SKI.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getSKIBytesFromCert
 *
 * @param cert
 * @return ski bytes from the given certificate
 *
 * @throws XMLSecurityException
 * @see java.security.cert.X509Extension#getExtensionValue(java.lang.String)
 */
public static byte[] getSKIBytesFromCert(X509Certificate cert)
    throws XMLSecurityException {

    if (cert.getVersion() < 3) {
        Object exArgs[] = { Integer.valueOf(cert.getVersion()) };
        throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
    }

    /*
     * Gets the DER-encoded OCTET string for the extension value
     * (extnValue) identified by the passed-in oid String. The oid
     * string is represented by a set of positive whole numbers
     * separated by periods.
     */
    byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID);
    if (extensionValue == null) {
        throw new XMLSecurityException("certificate.noSki.null");
    }

    /**
     * Strip away first four bytes from the extensionValue
     * The first two bytes are the tag and length of the extensionValue
     * OCTET STRING, and the next two bytes are the tag and length of
     * the ski OCTET STRING.
     */
    byte skidValue[] = new byte[extensionValue.length - 4];

    System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue));
    }

    return skidValue;
}
 
Example #26
Source File: PKITest.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
private VaultResponseData generateKeyPair(Date startDate, long valid) throws Exception {
    CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA");
    certGen.generate(2048);

    X500Name x500Name = new X500Name("CN=Test");
    X509Certificate cert = certGen.getSelfCertificate(x500Name, startDate, valid);


    byte[] encodedPrivateKey = certGen.getPrivateKey().getEncoded();
    byte[] encodedPublicKey = cert.getEncoded();

    String privateKeySb = "-----BEGIN PRIVATE KEY-----\n" +
            Base64.getMimeEncoder().encodeToString(encodedPrivateKey) +
            "\n-----END PRIVATE KEY-----";
    String publicKey = "-----BEGIN PUBLIC KEY-----\n" +
            Base64.getMimeEncoder().encodeToString(encodedPublicKey) +
            "\n-----END PUBLIC KEY-----";

    privateKeySb = privateKeySb.replaceAll("\\n", "\\\\n");
    privateKeySb = privateKeySb.replaceAll("\\r", "");

    publicKey = publicKey.replaceAll("\\n", "\\\\n");
    publicKey = publicKey.replaceAll("\\r", "");

    VaultResponseData vaultResponseData = new VaultResponseData();
    vaultResponseData.setPrivate_key(privateKeySb);
    vaultResponseData.setCertificate(publicKey);
    return vaultResponseData;
}
 
Example #27
Source File: XMLX509Certificate.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor XMLX509Certificate
 *
 * @param doc
 * @param x509certificate
 * @throws XMLSecurityException
 */
public XMLX509Certificate(Document doc, X509Certificate x509certificate)
    throws XMLSecurityException {
    super(doc);

    try {
        this.addBase64Text(x509certificate.getEncoded());
    } catch (java.security.cert.CertificateEncodingException ex) {
        throw new XMLSecurityException("empty", ex);
    }
}
 
Example #28
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static X509Certificate generateX509FromInputStream(InputStream instr) {
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BCFIPS");
        return (X509Certificate) certFactory.generateCertificate(instr);
    } catch (CertificateException | NoSuchProviderException ex) {
        logp(Level.SEVERE, classname, "generateX509FromBytes", "CRYPTO-MSG-1000", printStackTrace(ex));
    }
    return null;
}
 
Example #29
Source File: CompleteCertRefsVerifier.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public QualifyingProperty verify(
        CompleteCertificateRefsData propData,
        QualifyingPropertyVerificationContext ctx) throws InvalidPropertyException
{
    List<X509Certificate> caCerts = ctx.getCertChainData().getCertificateChain();
    caCerts = caCerts.subList(1, caCerts.size());
    Collection<CertRef> caCertRefs = propData.getCertRefs();

    // "Check that there are no references to certificates out of those that
    // are part of the certification path."

    for (X509Certificate caCert : caCerts)
    {
        CertRef caRef = CertRefUtils.findCertRef(caCert, caCertRefs, this.dnComparer);
        if (null == caRef)
            throw new CompleteCertRefsCertNotFoundException(caCert);
        try
        {
            CertRefUtils.checkCertRef(caRef, caCert, messageDigestProvider);
        } catch (CertRefUtils.InvalidCertRefException ex)
        {
            throw new CompleteCertRefsReferenceException(caCert, caRef, ex.getMessage());
        }
    }

    return new CompleteCertificateRefsProperty(Collections.unmodifiableList(caCerts));
}
 
Example #30
Source File: TlsCertificateDefinition.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public List<X509Certificate> certificates()
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException {
  final List<X509Certificate> results = Lists.newArrayList();

  final KeyStore p12 = loadP12KeyStore(pkcs12File, password);
  final Enumeration<String> aliases = p12.aliases();
  while (aliases.hasMoreElements()) {
    results.add((X509Certificate) p12.getCertificate(aliases.nextElement()));
  }
  return results;
}