/** * Tests whether given certificate contains public key or not. * * @param key Public key which we are looking for. * @param certs Certificate which should be tested. * @return {@code true} if certificate contains given key and * {@code false} if not. */ private static boolean findKeyInCertificates(PublicKey key, Certificate[] certs) { if (key == null || certs == null) return false; for (Certificate cert : certs) { if (cert.getPublicKey().equals(key)) return true; } return false; }
private static boolean matches(PrivateKey privateKey, Certificate certificate) { try { PublicKey publicKey = certificate.getPublicKey(); Signature signer = createSignature(privateKey, publicKey); signer.initSign(privateKey); signer.update(TEST_SIGNATURE_DATA); byte[] signature = signer.sign(); signer.initVerify(publicKey); signer.update(TEST_SIGNATURE_DATA); return signer.verify(signature); } catch (GeneralSecurityException ignored) { return false; } }
public static PublicKey getPublicKeyByX509(String x509File) { if (x509File == null || x509File.length() == 0) { return ConfigTools.getPublicKey(null); } FileInputStream in = null; try { in = new FileInputStream(x509File); CertificateFactory factory = CertificateFactory .getInstance("X.509"); Certificate cer = factory.generateCertificate(in); return cer.getPublicKey(); } catch (Exception e) { throw new IllegalArgumentException("Failed to get public key", e); } finally { JdbcUtils.close(in); } }
/** * Set the certificate. * * @param certificate the certificate (must not be {@code null}) * @return this builder instance */ public Builder setCertificate(final Certificate certificate) { Assert.checkNotNullParam("certificate", certificate); this.certificate = certificate; this.publicKey = certificate.getPublicKey(); return this; }
String generateRSAPublicKey() { RSAPublicKey pub = (RSAPublicKey) cert.getPublicKey(); StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.serialPubKeyType"), pub.getAlgorithm()); append(builder, NLS.str("certificate.serialPubKeyExponent"), pub.getPublicExponent().toString(10)); append(builder, NLS.str("certificate.serialPubKeyModulusSize"), Integer.toString( pub.getModulus().toString(2).length())); append(builder, NLS.str("certificate.serialPubKeyModulus"), pub.getModulus().toString(10)); return builder.toString(); }
/** * 从KeyStore中获取私钥公钥 * * @param keyStore {@link KeyStore} * @param password 密码 * @param alias 别名 * @return {@link KeyPair} * @since 4.4.1 */ public static KeyPair getKeyPair(KeyStore keyStore, char[] password, String alias) { PublicKey publicKey; PrivateKey privateKey; try { publicKey = keyStore.getCertificate(alias).getPublicKey(); privateKey = (PrivateKey) keyStore.getKey(alias, password); } catch (Exception e) { throw new CryptoException(e); } return new KeyPair(publicKey, privateKey); }
/** * 从KeyStore中获取私钥公钥 * * @param keyStore {@link KeyStore} * @param password 密码 * @param alias 别名 * @return {@link KeyPair} * @since 4.4.1 */ public static KeyPair getKeyPair(KeyStore keyStore, char[] password, String alias) { PublicKey publicKey; PrivateKey privateKey; try { publicKey = keyStore.getCertificate(alias).getPublicKey(); privateKey = (PrivateKey) keyStore.getKey(alias, password); } catch (Exception e) { throw new CryptoException(e); } return new KeyPair(publicKey, privateKey); }
boolean verifySigned(File keystore, Certificate agentCertificate) { try { KeyStore store = KeyStore.getInstance("JKS"); FileInputStream inputStream = new FileInputStream(keystore); store.load(inputStream, PASSWORD_AS_CHAR_ARRAY); IOUtils.closeQuietly(inputStream); KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store.getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY)); Certificate intermediateCertificate = intermediateEntry.getCertificate(); agentCertificate.verify(intermediateCertificate.getPublicKey()); return true; } catch (Exception e) { return false; } }
final Certificate[] peerCertificates = sslSession.getPeerCertificates(); final Certificate certificate = peerCertificates[0]; final String certificateAlgorithm = certificate.getPublicKey().getAlgorithm();
String generateDSAPublicKey() { DSAPublicKey pub = (DSAPublicKey) cert.getPublicKey(); StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.serialPubKeyType"), pub.getAlgorithm()); append(builder, NLS.str("certificate.serialPubKeyY"), pub.getY().toString(10)); return builder.toString(); }
@Override public void setKeyStoreEntry(KeyStore.PrivateKeyEntry entry) { this.key_pair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); }
public ConsumerDetails getObject() throws Exception { if ("rsa-cert".equals(typeOfSecret)) { try { Certificate cert = CertificateFactory.getInstance("X.509").generateCertificate(resourceLoader.getResource(secret).getInputStream()); consumer.setSignatureSecret(new RSAKeySecret(cert.getPublicKey())); } catch (IOException e) { throw new BeanCreationException("RSA certificate not found at " + secret + ".", e); } catch (CertificateException e) { throw new BeanCreationException("Invalid RSA certificate at " + secret + ".", e); } catch (NullPointerException e) { throw new BeanCreationException("Could not load RSA certificate at " + secret + ".", e); } } else { consumer.setSignatureSecret(new SharedConsumerSecretImpl(secret)); } return consumer; }
cert = certfac.generateCertificate(bis); rsaPubKey = (RSAPublicKey) cert.getPublicKey(); } catch (final Exception ex) { LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_CANNOT_OBTAIN_PUBLIC_KEY(), ex);
PublicKey publicKey = certificate.getPublicKey();
certs.append("\n\n-----BEGIN CERTIFICATE-----\n"); certs.append(DatatypeConverter.printBase64Binary( certificate.getPublicKey().getEncoded()).replaceAll("(.{64})", "$1\n")); certs.append("\n-----END CERTIFICATE-----\n\n");
/** * 设置{@link Certificate} 为PublicKey<br> * 如果Certificate是X509Certificate,我们需要检查是否有密钥扩展 * * @param certificate {@link Certificate} * @return this */ public Sign setCertificate(Certificate certificate) { // If the certificate is of type X509Certificate, // we should check whether it has a Key Usage // extension marked as critical. if (certificate instanceof java.security.cert.X509Certificate) { // Check whether the cert has a key usage extension // marked as a critical extension. // The OID for KeyUsage extension is 2.5.29.15. final X509Certificate cert = (X509Certificate) certificate; final Set<String> critSet = cert.getCriticalExtensionOIDs(); if (CollUtil.isNotEmpty(critSet) && critSet.contains("2.5.29.15")) { final boolean[] keyUsageInfo = cert.getKeyUsage(); // keyUsageInfo[0] is for digitalSignature. if ((keyUsageInfo != null) && (keyUsageInfo[0] == false)) { throw new CryptoException("Wrong key usage"); } } } this.publicKey = certificate.getPublicKey(); return this; } }
/** * 设置{@link Certificate} 为PublicKey<br> * 如果Certificate是X509Certificate,我们需要检查是否有密钥扩展 * * @param certificate {@link Certificate} * @return this */ public Sign setCertificate(Certificate certificate) { // If the certificate is of type X509Certificate, // we should check whether it has a Key Usage // extension marked as critical. if (certificate instanceof java.security.cert.X509Certificate) { // Check whether the cert has a key usage extension // marked as a critical extension. // The OID for KeyUsage extension is 2.5.29.15. final X509Certificate cert = (X509Certificate) certificate; final Set<String> critSet = cert.getCriticalExtensionOIDs(); if (CollUtil.isNotEmpty(critSet) && critSet.contains("2.5.29.15")) { final boolean[] keyUsageInfo = cert.getKeyUsage(); // keyUsageInfo[0] is for digitalSignature. if ((keyUsageInfo != null) && (keyUsageInfo[0] == false)) { throw new CryptoException("Wrong key usage"); } } } this.publicKey = certificate.getPublicKey(); return this; } }
@Override public SingleSignOnSessionFactory get() { KeyStore store = this.keyStore.get(); String alias = this.keyAlias; CredentialSource source = this.credentialSource.get(); try { if (!store.containsAlias(alias)) { throw UndertowLogger.ROOT_LOGGER.missingKeyStoreEntry(alias); } if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { throw UndertowLogger.ROOT_LOGGER.keyStoreEntryNotPrivate(alias); } PasswordCredential credential = source.getCredential(PasswordCredential.class); if (credential == null) { throw UndertowLogger.ROOT_LOGGER.missingCredential(source.toString()); } ClearPassword password = credential.getPassword(ClearPassword.class); if (password == null) { throw UndertowLogger.ROOT_LOGGER.credentialNotClearPassword(credential.toString()); } KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword())); KeyPair keyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); Optional<SSLContext> context = Optional.ofNullable(this.sslContext).map(dependency -> dependency.get()); return new DefaultSingleSignOnSessionFactory(this.manager.get(), keyPair, connection -> context.ifPresent(ctx -> connection.setSSLSocketFactory(ctx.getSocketFactory()))); } catch (GeneralSecurityException | IOException e) { throw new IllegalArgumentException(e); } } }
cert.verify(caCert.getPublicKey());
@Override public CipherAuthToken apply(String authValue) { KeyStore store = this.keyStore.get(); String alias = this.keyAlias; try { if (!store.containsAlias(alias)) { throw JGroupsLogger.ROOT_LOGGER.keyEntryNotFound(alias); } if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { throw JGroupsLogger.ROOT_LOGGER.unexpectedKeyStoreEntryType(alias, KeyStore.PrivateKeyEntry.class.getSimpleName()); } PasswordCredential credential = this.keyCredentialSource.get().getCredential(PasswordCredential.class); if (credential == null) { throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource(); } ClearPassword password = credential.getPassword(ClearPassword.class); if (password == null) { throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource(); } KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword())); KeyPair pair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); Cipher cipher = Cipher.getInstance(this.transformation); return new CipherAuthToken(cipher, pair, authValue.getBytes(StandardCharsets.UTF_8)); } catch (GeneralSecurityException | IOException e) { throw new IllegalArgumentException(e); } } }