java.security.cert.CertificateException Java Examples

The following examples show how to use java.security.cert.CertificateException. 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: PostHTTP.java    From localization_nifi with Apache License 2.0 7 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    builder = builder.useProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example #2
Source File: GPCrypto.java    From GlobalPlatformPro with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static PublicKey pem2PublicKey(InputStream in) throws IOException {
    try (PEMParser pem = new PEMParser(new InputStreamReader(in, StandardCharsets.US_ASCII))) {
        Object ohh = pem.readObject();
        if (ohh instanceof PEMKeyPair) {
            PEMKeyPair kp = (PEMKeyPair) ohh;
            return new JcaPEMKeyConverter().getKeyPair(kp).getPublic();
        } else if (ohh instanceof SubjectPublicKeyInfo) {
            return new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) ohh);
        } else if (ohh instanceof X509CertificateHolder) {
            X509CertificateHolder certHolder = (X509CertificateHolder) ohh;
            try {
                return new JcaX509CertificateConverter().getCertificate(certHolder).getPublicKey();
            } catch (CertificateException ce) {
                throw new IllegalArgumentException("Can not read PEM: " + ce.getMessage());
            }
        } else throw new IllegalArgumentException("Can not read PEM");
    }
}
 
Example #3
Source File: OIDMap.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add a name to lookup table.
 *
 * @param name the name of the attr
 * @param oid the string representation of the object identifier for
 *         the class.
 * @param clazz the Class object associated with this attribute
 * @exception CertificateException on errors.
 */
public static void addAttribute(String name, String oid, Class<?> clazz)
        throws CertificateException {
    ObjectIdentifier objId;
    try {
        objId = new ObjectIdentifier(oid);
    } catch (IOException ioe) {
        throw new CertificateException
                            ("Invalid Object identifier: " + oid);
    }
    OIDInfo info = new OIDInfo(name, objId, clazz);
    if (oidMap.put(objId, info) != null) {
        throw new CertificateException
                            ("Object identifier already exists: " + oid);
    }
    if (nameMap.put(name, info) != null) {
        throw new CertificateException("Name already exists: " + name);
    }
}
 
Example #4
Source File: SSLUtil.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private void checkTrusted(Func func) throws CertificateException {
    CertificateException ex = null;
    for (int i =0; i < list.size(); ++i) {
        X509TrustManager tm = list.get(i);
        try {
            func.apply(tm);
            // accepted
            return;
        } catch (CertificateException e) {
            if(ex == null || Throwables.has(e, CertPathValidatorException.class)) {
                ex = e;
            }
        }
    }
    if(ex != null) {
        throw ex;
    }
}
 
Example #5
Source File: SignatureFileVerifier.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * process the signature block file. Goes through the .SF file
 * and adds code signers for each section where the .SF section
 * hash was verified against the Manifest section.
 *
 *
 */
public void process(Hashtable<String, CodeSigner[]> signers,
        List<Object> manifestDigests)
    throws IOException, SignatureException, NoSuchAlgorithmException,
        JarException, CertificateException
{
    // calls Signature.getInstance() and MessageDigest.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        processImpl(signers, manifestDigests);
    } finally {
        Providers.stopJarVerification(obj);
    }

}
 
Example #6
Source File: S3SessionTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTrustChain() throws Exception {
    final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials(
        System.getProperties().getProperty("s3.key"), System.getProperties().getProperty("s3.secret")
    ));
    final AtomicBoolean verified = new AtomicBoolean();
    final S3Session session = new S3Session(host, new DefaultX509TrustManager() {
        @Override
        public void verify(final String hostname, final X509Certificate[] certs, final String cipher) throws CertificateException {
            verified.set(true);
            super.verify(hostname, certs, cipher);
        }
    },
        new KeychainX509KeyManager(new DisabledCertificateIdentityCallback(), host, new DisabledCertificateStore()));
    final LoginConnectionService c = new LoginConnectionService(
        new DisabledLoginCallback(),
        new DisabledHostKeyCallback(),
        new DisabledPasswordStore(),
        new DisabledProgressListener()
    );
    c.connect(session, PathCache.empty(), new DisabledCancelCallback());
    assertTrue(verified.get());
    session.close();
}
 
Example #7
Source File: HttpResponseCache.java    From reader with MIT License 6 votes vote down vote up
private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
  int length = reader.readInt();
  if (length == -1) {
    return null;
  }
  try {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Certificate[] result = new Certificate[length];
    for (int i = 0; i < result.length; i++) {
      String line = reader.readLine();
      byte[] bytes = Base64.decode(line.getBytes("US-ASCII"));
      result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
    }
    return result;
  } catch (CertificateException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example #8
Source File: StandardKnoxConfiguration.java    From nifi with Apache License 2.0 6 votes vote down vote up
public RSAPublicKey getKnoxPublicKey() {
    // get the path to the public key
    final Path knoxPublicKeyPath = properties.getKnoxPublicKeyPath();

    // ensure the file exists
    if (Files.isRegularFile(knoxPublicKeyPath) && Files.exists(knoxPublicKeyPath)) {
        try (final InputStream publicKeyStream = Files.newInputStream(knoxPublicKeyPath)) {
            final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(publicKeyStream);
            return (RSAPublicKey) certificate.getPublicKey();
        } catch (final IOException | CertificateException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } else {
        throw new RuntimeException(String.format("The specified Knox public key path does not exist '%s'", knoxPublicKeyPath.toString()));
    }
}
 
Example #9
Source File: SESealTest.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
@Test
    public void verify() throws IOException, NoSuchAlgorithmException, CertificateException, InvalidKeyException, SignatureException {
        Path path = Paths.get("target", "UserV1.esl");
//        Path path = Paths.get("target", "2_980_1587284330714.es");

        SESeal seal = SESeal.getInstance(Files.readAllBytes(path));
        SES_SignInfo signInfo = seal.getSignInfo();

        ASN1OctetString cert = signInfo.getCert();
        CertificateFactory factory = new CertificateFactory();
        X509Certificate certificate = (X509Certificate) factory.engineGenerateCertificate(cert.getOctetStream());

        ASN1EncodableVector v = new ASN1EncodableVector(3);
        v.add(seal.getEsealInfo());
        v.add(cert);
        v.add(signInfo.getSignatureAlgorithm());

        Signature sg = Signature.getInstance("SM3WithSM2", new BouncyCastleProvider());
        sg.initVerify(certificate);
        sg.update(new DERSequence(v).getEncoded("DER"));
        byte[] sigVal = signInfo.getSignData().getBytes();
        System.out.println(sg.verify(sigVal));
    }
 
Example #10
Source File: IdentityCertificateService.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Create a certificate using key pair and signing certificate with CA certificate, common name and a list of subjective alternate name
 *
 * @return signed sever identity certificate
 * */
@Override
public X509Certificate createSignedCertificate(PublicKey publicKey, PrivateKey privateKey, String commonName,
    List<ASN1Encodable> sans)
    throws CertificateException, IOException, OperatorCreationException, NoSuchProviderException,
           NoSuchAlgorithmException, InvalidKeyException, SignatureException {
  X500Name issuer = new X509CertificateHolder(_issuerCertificate.getEncoded()).getSubject();
  BigInteger serial = getSerial();
  X500Name subject = getSubject(commonName);

  X509v3CertificateBuilder x509v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(issuer, serial, getValidDateFrom(), getValidDateTo(), subject, publicKey);
  buildExtensions(x509v3CertificateBuilder, publicKey);

  fillSans(sans, x509v3CertificateBuilder);

  X509Certificate signedCertificate = createCertificate(_issuerPrivateKey, x509v3CertificateBuilder);

  signedCertificate.checkValidity();
  signedCertificate.verify(_issuerCertificate.getPublicKey());

  return signedCertificate;
}
 
Example #11
Source File: ParsedAttestationRecordTest.java    From android-key-attestation with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseAttestationRecord() throws CertificateException, IOException {
  X509Certificate x509Certificate = getAttestationRecord(CERT);
  ParsedAttestationRecord attestationRecord =
      ParsedAttestationRecord.createParsedAttestationRecord(x509Certificate);

  assertThat(attestationRecord.attestationVersion).isEqualTo(EXPECTED_ATTESTATION_VERSION);
  assertThat(attestationRecord.attestationSecurityLevel)
      .isEqualTo(EXPECTED_ATTESTATION_SECURITY_LEVEL);
  assertThat(attestationRecord.keymasterVersion).isEqualTo(EXPECTED_KEYMASTER_VERSION);
  assertThat(attestationRecord.keymasterSecurityLevel)
      .isEqualTo(EXPECTED_KEYMASTER_SECURITY_LEVEL);
  assertThat(attestationRecord.attestationChallenge).isEqualTo(EXPECTED_ATTESTATION_CHALLENGE);
  assertThat(attestationRecord.uniqueId).isEqualTo(EXPECTED_UNIQUE_ID);
  assertThat(attestationRecord.softwareEnforced).isNotNull();
  assertThat(attestationRecord.teeEnforced).isNotNull();
}
 
Example #12
Source File: ConfigurableX509TrustManager.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
public void checkServerTrusted(X509Certificate[] certificates, String type)
throws CertificateException {
    if (this.trustLevel.equals(TrustLevel.OPEN)) {
        return;
    }

    try {
        this.standardTrustManager.checkServerTrusted(certificates, type);
        if (this.trustLevel.equals(TrustLevel.STRICT)) {
            logger.severe(TrustLevel.STRICT + " not implemented.");
        }
    } catch (CertificateException e) {
        if (this.trustLevel.equals(TrustLevel.LOOSE) &&
            certificates != null && certificates.length == 1)
        {
                // If only one cert and its valid and it caused a
                // CertificateException, assume its selfsigned.
                X509Certificate certificate = certificates[0];
                certificate.checkValidity();
        } else {
            // If we got to here, then we're probably NORMAL. Rethrow.
            throw e;
        }
    }
}
 
Example #13
Source File: OIDMap.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add a name to lookup table.
 *
 * @param name the name of the attr
 * @param oid the string representation of the object identifier for
 *         the class.
 * @param clazz the Class object associated with this attribute
 * @exception CertificateException on errors.
 */
public static void addAttribute(String name, String oid, Class<?> clazz)
        throws CertificateException {
    ObjectIdentifier objId;
    try {
        objId = new ObjectIdentifier(oid);
    } catch (IOException ioe) {
        throw new CertificateException
                            ("Invalid Object identifier: " + oid);
    }
    OIDInfo info = new OIDInfo(name, objId, clazz);
    if (oidMap.put(objId, info) != null) {
        throw new CertificateException
                            ("Object identifier already exists: " + oid);
    }
    if (nameMap.put(name, info) != null) {
        throw new CertificateException("Name already exists: " + name);
    }
}
 
Example #14
Source File: PrivateKeyUsageExtension.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set the attribute value.
 * @exception CertificateException on attribute handling errors.
 */
public void set(String name, Object obj)
throws CertificateException, IOException {
    if (!(obj instanceof Date)) {
        throw new CertificateException("Attribute must be of type Date.");
    }
    if (name.equalsIgnoreCase(NOT_BEFORE)) {
        notBefore = (Date)obj;
    } else if (name.equalsIgnoreCase(NOT_AFTER)) {
        notAfter = (Date)obj;
    } else {
      throw new CertificateException("Attribute name not recognized by"
                       + " CertAttrSet:PrivateKeyUsage.");
    }
    encodeThis();
}
 
Example #15
Source File: ZookeeperLeaderFinder.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the cluster CA certificate(s) passed in the given Secret
 * and return the PemTrustOptions for trusting them.
 */
protected PemTrustOptions trustOptions(Secret clusterCaCertificateSecret) {
    Base64.Decoder decoder = Base64.getDecoder();
    CertificateFactory x509 = x509Factory();
    PemTrustOptions pto = new PemTrustOptions();
    for (Map.Entry<String, String> entry : clusterCaCertificateSecret.getData().entrySet()) {
        String entryName = entry.getKey();
        if (entryName.endsWith(".crt")) {
            log.info("Trusting certificate {} from Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
            byte[] certBytes = decoder.decode(entry.getValue());
            try {
                x509.generateCertificate(new ByteArrayInputStream(certBytes));
            } catch (CertificateException e) {
                throw corruptCertificate(clusterCaCertificateSecret, entryName, e);
            }
            pto.addCertValue(Buffer.buffer(certBytes));
        } else {
            log.warn("Ignoring non-certificate {} in Secret {}", entryName, clusterCaCertificateSecret.getMetadata().getName());
        }
    }
    return pto;
}
 
Example #16
Source File: KeyStoreFileTrustAnchorsProvider.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Map<AAGUID, Set<TrustAnchor>> loadTrustAnchors() {
    checkConfig();
    Path keystore = getKeyStore();
    try (InputStream inputStream = Files.newInputStream(keystore)) {
        KeyStore keyStoreObject = loadKeyStoreFromStream(inputStream, getPassword());
        List<String> aliases = Collections.list(keyStoreObject.aliases());
        Set<TrustAnchor> trustAnchors = new HashSet<>();
        for (String alias : aliases) {
            X509Certificate certificate = (X509Certificate) keyStoreObject.getCertificate(alias);
            trustAnchors.add(new TrustAnchor(certificate, null));
        }
        return Collections.singletonMap(AAGUID.NULL, trustAnchors);
    } catch (java.security.KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new KeyStoreException("Failed to load TrustAnchor from keystore", e);
    }
}
 
Example #17
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static DatabaseClient getDatabaseClient(String user, String password, ConnectionType connType)
		throws KeyManagementException, NoSuchAlgorithmException, IOException {
	DatabaseClient client = null;
	
	SSLContext sslcontext = null;
	SecurityContext secContext = new DatabaseClientFactory.DigestAuthContext(user,password);
	if (IsSecurityEnabled()) {
		try {
			sslcontext = getSslContext();
		} catch (UnrecoverableKeyException | KeyStoreException | CertificateException e) {
			e.printStackTrace();
		}
		secContext = secContext.withSSLContext(sslcontext).withSSLHostnameVerifier(SSLHostnameVerifier.ANY);
	}
		client = DatabaseClientFactory.newClient(getRestServerHostName(), getRestServerPort(),
				secContext, connType);				
	return client;
}
 
Example #18
Source File: TrustManagerFactoryFactory.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private TrustManagerFactory createTrustManagerFactory(@Nullable final String trustedCertificates)
        throws NoSuchAlgorithmException, CertificateException, KeyStoreException,
        InvalidAlgorithmParameterException {
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(PKIX);
    if (trustedCertificates != null) {
        final KeyStore keystore = keyStoreFactory.newKeystore();
        final Collection<? extends Certificate> caCerts;
        final byte[] caCertsPem = trustedCertificates.getBytes(StandardCharsets.US_ASCII);
        caCerts = X509_CERTIFICATE_FACTORY.generateCertificates(new ByteArrayInputStream(caCertsPem));
        long cnt = 0;
        for (final Certificate caCert : caCerts) {
            keystore.setCertificateEntry("ca-" + cnt++, caCert);
        }
        trustManagerFactory.init(keystore);
    } else {
        // standard CAs; add revocation check
        final PKIXRevocationChecker revocationChecker =
                (PKIXRevocationChecker) CertPathBuilder.getInstance(PKIX).getRevocationChecker();
        final PKIXBuilderParameters parameters =
                new PKIXBuilderParameters(DEFAULT_CA_KEYSTORE, new X509CertSelector());
        parameters.addCertPathChecker(revocationChecker);
        trustManagerFactory.init(new CertPathTrustManagerParameters(parameters));
    }
    return trustManagerFactory;
}
 
Example #19
Source File: AppBuilderBase.java    From buck with Apache License 2.0 6 votes vote down vote up
protected PrivateKeyAndCertificate createKeystoreProperties()
    throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
  KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
  KeystoreProperties keystoreProperties = keystorePropertiesSupplier.get();
  char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
  try {
    keystore.load(filesystem.getInputStreamForRelativePath(pathToKeystore), keystorePassword);
  } catch (NoSuchAlgorithmException | CertificateException e) {
    throw new HumanReadableException(e, "%s is an invalid keystore.", pathToKeystore);
  }

  String alias = keystoreProperties.getAlias();
  char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
  Key key = keystore.getKey(alias, keyPassword);
  // key can be null if alias/password is incorrect.
  if (key == null) {
    throw new HumanReadableException(
        "The keystore [%s] key.alias [%s] does not exist or does not identify a key-related "
            + "entry",
        pathToKeystore, alias);
  }

  Certificate certificate = keystore.getCertificate(alias);

  return new PrivateKeyAndCertificate((PrivateKey) key, (X509Certificate) certificate);
}
 
Example #20
Source File: BadPem.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    byte[] cert = keyStore.getCertificate(alias).getEncoded();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(bout);
    byte[] CRLF = new byte[] {'\r', '\n'};
    pout.println(X509Factory.BEGIN_CERT);
    for (int i=0; i<cert.length; i += 48) {
        int blockLen = (cert.length > i + 48) ? 48 : (cert.length - i);
        pout.println("!" + Base64.getEncoder()
                .encodeToString(Arrays.copyOfRange(cert, i, i + blockLen)));
    }
    pout.println(X509Factory.END_CERT);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    try {
        cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray()));
        throw new Exception("Should fail");
    } catch (CertificateException e) {
        // Good
    }
}
 
Example #21
Source File: CertificateExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>CertificateException(Throwable)</code> constructor
 * Assertion: constructs CertificateException when <code>cause</code> is
 * null
 */
public void testCertificateException04() {
    Throwable cause = null;
    CertificateException tE = new CertificateException(cause);
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
 
Example #22
Source File: ServerCrypto.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {

        try {

            // Generate cert path
            java.util.List certList = java.util.Arrays.asList(certs);
            CertPath path = this.getCertificateFactory().generateCertPath(certList);

            // Use the certificates in the keystore as TrustAnchors
            PKIXParameters param = new PKIXParameters(ks);

            // Do not check a revocation list
            param.setRevocationEnabled(false);

            // Verify the trust path using the above settings
            String provider = properties
                    .getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
            CertPathValidator certPathValidator;
            if (provider == null || provider.length() == 0) {
                certPathValidator = CertPathValidator.getInstance("PKIX");
            } else {
                certPathValidator = CertPathValidator.getInstance("PKIX", provider);
            }
            certPathValidator.validate(path, param);
        } catch (NoSuchProviderException | NoSuchAlgorithmException | CertificateException |
                InvalidAlgorithmParameterException | CertPathValidatorException | KeyStoreException ex) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "certpath",
                    new Object[]{ex.getMessage()}, ex);
        }
        return true;
    }
 
Example #23
Source File: HttpsUtils.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    try {
        defaultTrustManager.checkServerTrusted(chain, authType);
    } catch (CertificateException ce) {
        localTrustManager.checkServerTrusted(chain, authType);
    }
}
 
Example #24
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 #25
Source File: Client.java    From xipki with Apache License 2.0 5 votes vote down vote up
public List<X509Cert> scepGetCert(PrivateKey identityKey, X509Cert identityCert,
    X500Name issuer, BigInteger serialNumber) throws ScepClientException {
  Args.notNull(identityKey, "identityKey");
  Args.notNull(identityCert, "identityCert");
  Args.notNull(issuer, "issuer");
  Args.notNull(serialNumber, "serialNumber");

  initIfNotInited();

  PkiMessage request = new PkiMessage(TransactionId.randomTransactionId(), MessageType.GetCert);

  IssuerAndSerialNumber isn = new IssuerAndSerialNumber(issuer, serialNumber);
  request.setMessageData(isn);
  ContentInfo envRequest = encryptThenSign(request, identityKey, identityCert);
  ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, envRequest);

  CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
  DecodedPkiMessage response = decode(cmsSignedData, identityKey, identityCert);
  if (response.getPkiStatus() != PkiStatus.SUCCESS) {
    throw new ScepClientException("server returned " + response.getPkiStatus());
  }

  ContentInfo messageData = ContentInfo.getInstance(response.getMessageData());
  try {
    return ScepUtil.getCertsFromSignedData(SignedData.getInstance(messageData.getContent()));
  } catch (CertificateException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example #26
Source File: ConnectorCertificateChecker.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean isCertificateRevoked(File certFile, DateTime validOn) throws TechnicalConnectorException {
   try {
      CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
      X509Certificate cert = (X509Certificate)certFactory.generateCertificate(new FileInputStream(certFile));
      return this.isCertificateRevoked(cert, validOn);
   } catch (FileNotFoundException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   } catch (CertificateException var6) {
      throw new CertificateVerificationException(var6.getMessage(), var6);
   }
}
 
Example #27
Source File: PackedAttestation.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public PackedAttestation() {
  try {
    sha256 = MessageDigest.getInstance("SHA-256");
    x509 = CertificateFactory.getInstance("X.509");
    sig = Signature.getInstance("SHA256withECDSA");
  } catch (NoSuchAlgorithmException | CertificateException e) {
    throw new AttestationException(e);
  }
}
 
Example #28
Source File: NetworkSecurityTrustManager.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType, Socket socket)
        throws CertificateException {
    List<X509Certificate> trustedChain =
            mDelegate.getTrustedChainForServer(certs, authType, socket);
    checkPins(trustedChain);
}
 
Example #29
Source File: GApp.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    try {
        for (X509Certificate certificate : chain) {
            certificate.checkValidity(); //检查证书是否过期,签名是否通过等
        }
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
 
Example #30
Source File: CertificateFactory1Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>generateCertPath(List certificates)</code> method
 * Assertion: returns empty CertPath if certificates is empty
 */
public void testCertificateFactory15() throws CertificateException {
    if (!X509Support) {
        fail(NotSupportMsg);
        return;
    }
    CertificateFactory[] certFs = initCertFs();
    assertNotNull("CertificateFactory objects were not created", certFs);
    List<Certificate> list = new Vector<Certificate>();
    for (int i = 0; i < certFs.length; i++) {
        CertPath cp = certFs[i].generateCertPath(list);
        List<? extends Certificate> list1 = cp.getCertificates();
        assertTrue("List should be empty", list1.isEmpty());
    }
}