java.security.cert.X509Certificate类的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(15.3k)|赞(0)|评价(0)|浏览(344)

本文整理了Java中java.security.cert.X509Certificate类的一些代码示例,展示了X509Certificate类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。X509Certificate类的具体详情如下:
包路径:java.security.cert.X509Certificate
类名称:X509Certificate

X509Certificate介绍

[英]Abstract base class for X.509 certificates.

This represents a standard way for accessing the attributes of X.509 certificates.

The basic X.509 v3 format described in ASN.1:

Certificate  ::=  SEQUENCE  { 
tbsCertificate       TBSCertificate, 
signatureAlgorithm   AlgorithmIdentifier, 
signature            BIT STRING  } 
TBSCertificate  ::=  SEQUENCE  { 
version         [0]  EXPLICIT Version DEFAULT v1, 
serialNumber         CertificateSerialNumber, 
signature            AlgorithmIdentifier, 
issuer               Name, 
validity             Validity, 
subject              Name, 
subjectPublicKeyInfo SubjectPublicKeyInfo, 
issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL, 
-- If present, version must be v2 or v3 
subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL, 
-- If present, version must be v2 or v3 
extensions      [3]  EXPLICIT Extensions OPTIONAL 
-- If present, version must be v3 
}

For more information consult RFC 2459 "Internet X.509 Public Key Infrastructure Certificate and CRL Profile" at http://www.ietf.org/rfc/rfc2459.txt .
[中]X.509证书的抽象基类。
这代表了访问X.509证书属性的标准方式。
ASN中描述的基本X.509 v3格式。1:

Certificate  ::=  SEQUENCE  { 
tbsCertificate       TBSCertificate, 
signatureAlgorithm   AlgorithmIdentifier, 
signature            BIT STRING  } 
TBSCertificate  ::=  SEQUENCE  { 
version         [0]  EXPLICIT Version DEFAULT v1, 
serialNumber         CertificateSerialNumber, 
signature            AlgorithmIdentifier, 
issuer               Name, 
validity             Validity, 
subject              Name, 
subjectPublicKeyInfo SubjectPublicKeyInfo, 
issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL, 
-- If present, version must be v2 or v3 
subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL, 
-- If present, version must be v2 or v3 
extensions      [3]  EXPLICIT Extensions OPTIONAL 
-- If present, version must be v3 
}

有关更多信息,请咨询RFC 2459“Internet X.509公钥基础设施证书和CRL配置文件”,网址为http://www.ietf.org/rfc/rfc2459.txt

代码示例

代码示例来源:origin: prestodb/presto

public static KeyStore loadTrustStore(File certificateChainFile)
    throws IOException, GeneralSecurityException
{
  KeyStore keyStore = KeyStore.getInstance("JKS");
  keyStore.load(null, null);
  List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
  for (X509Certificate certificate : certificateChain) {
    X500Principal principal = certificate.getSubjectX500Principal();
    keyStore.setCertificateEntry(principal.getName("RFC2253"), certificate);
  }
  return keyStore;
}

代码示例来源:origin: square/okhttp

/** Returns true if {@code toVerify} was signed by {@code signingCert}'s public key. */
private boolean verifySignature(X509Certificate toVerify, X509Certificate signingCert) {
 if (!toVerify.getIssuerDN().equals(signingCert.getSubjectDN())) return false;
 try {
  toVerify.verify(signingCert.getPublicKey());
  return true;
 } catch (GeneralSecurityException verifyFailed) {
  return false;
 }
}

代码示例来源:origin: robovm/robovm

/**
 * Returns the {@code subject} (subject distinguished name) as an {@code
 * X500Principal}.
 *
 * @return the {@code subject} (subject distinguished name)
 */
public X500Principal getSubjectX500Principal() {
  try {
    // TODO if there is no X.509 certificate provider installed
    // should we try to access Harmony X509CertImpl via classForName?
    CertificateFactory factory = CertificateFactory
        .getInstance("X.509");
    X509Certificate cert = (X509Certificate) factory
        .generateCertificate(new ByteArrayInputStream(getEncoded()));
    return cert.getSubjectX500Principal();
  } catch (Exception e) {
    throw new RuntimeException("Failed to get X500Principal subject", e);
  }
}

代码示例来源:origin: square/okhttp

/** Returns the trusted CA certificate that signed {@code cert}. */
private X509Certificate findByIssuerAndSignature(X509Certificate cert) {
 X500Principal issuer = cert.getIssuerX500Principal();
 Set<X509Certificate> subjectCaCerts = subjectToCaCerts.get(issuer);
 if (subjectCaCerts == null) return null;
 for (X509Certificate caCert : subjectCaCerts) {
  PublicKey publicKey = caCert.getPublicKey();
  try {
   cert.verify(publicKey);
   return caCert;
  } catch (Exception ignored) {
  }
 }
 return null;
}

代码示例来源:origin: neo4j/neo4j

private String describeCertificate( X509Certificate certificate )
{
  return "Subject: " + certificate.getSubjectDN() +
      ", Issuer: " + certificate.getIssuerDN();
}

代码示例来源:origin: apache/geode

/**
 * Populate the available server public keys into a local static HashMap. This method is not
 * thread safe.
 */
public static void initCertsMap(Properties props) throws Exception {
 certificateMap = new HashMap();
 certificateFilePath = props.getProperty(PUBLIC_KEY_FILE_PROP);
 if (certificateFilePath != null && certificateFilePath.length() > 0) {
  KeyStore ks = KeyStore.getInstance("JKS");
  String keyStorePass = props.getProperty(PUBLIC_KEY_PASSWD_PROP);
  char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
  FileInputStream keystorefile = new FileInputStream(certificateFilePath);
  try {
   ks.load(keystorefile, passPhrase);
  } finally {
   keystorefile.close();
  }
  Enumeration aliases = ks.aliases();
  while (aliases.hasMoreElements()) {
   String alias = (String) aliases.nextElement();
   Certificate cert = ks.getCertificate(alias);
   if (cert instanceof X509Certificate) {
    String subject = ((X509Certificate) cert).getSubjectDN().getName();
    certificateMap.put(subject, cert);
   }
  }
 }
}

代码示例来源:origin: stackoverflow.com

public class TestClass {
  public static void main(String[] args) throws Exception {

    KeyStore p12 = KeyStore.getInstance("pkcs12");
    p12.load(new FileInputStream("pkcs.p12"), "password".toCharArray());
    Enumeration e = p12.aliases();
    while (e.hasMoreElements()) {
      String alias = (String) e.nextElement();
      X509Certificate c = (X509Certificate) p12.getCertificate(alias);
      Principal subject = c.getSubjectDN();
      String subjectArray[] = subject.toString().split(",");
      for (String s : subjectArray) {
        String[] str = s.trim().split("=");
        String key = str[0];
        String value = str[1];
        System.out.println(key + " - " + value);
      }
    }
  }
}

代码示例来源:origin: jooby-project/jooby

TrustManagerFactory trustManagerFactory)
   throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
   .generateCertificate(new ByteArrayInputStream(buf.array()));
 X500Principal principal = cert.getSubjectX500Principal();
 ks.setCertificateEntry(principal.getName("RFC2253"), cert);

代码示例来源:origin: Javen205/IJPay

/**
 * 通过keystore获取私钥证书的certId值
 * @param keyStore
 * @return
 */
private static String getCertIdIdByStore(KeyStore keyStore) {
  Enumeration<String> aliasenum = null;
  try {
    aliasenum = keyStore.aliases();
    String keyAlias = null;
    if (aliasenum.hasMoreElements()) {
      keyAlias = aliasenum.nextElement();
    }
    X509Certificate cert = (X509Certificate) keyStore
        .getCertificate(keyAlias);
    return cert.getSerialNumber().toString();
  } catch (KeyStoreException e) {
    LogUtil.writeErrorLog("getCertIdIdByStore Error", e);
    return null;
  }
}

代码示例来源:origin: apache/nifi

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());
    final String alias = keystore.aliases().nextElement();
    final Certificate cert = keystore.getCertificate(alias);
    if (cert instanceof X509Certificate) {
      principal = ((X509Certificate) cert).getSubjectDN();
    }
  }
  builder = builder.setProtocol(service.getSslAlgorithm());
  final SSLContext sslContext = builder.build();
  return sslContext;
}

代码示例来源:origin: apache/geode

/**
 * Load the private key of the server. This method is not thread safe.
 */
public static void initPrivateKey(Properties props) throws Exception {
 String privateKeyFilePath = props.getProperty(PRIVATE_KEY_FILE_PROP);
 privateKeyAlias = "";
 privateKeyEncrypt = null;
 if (privateKeyFilePath != null && privateKeyFilePath.length() > 0) {
  KeyStore ks = KeyStore.getInstance("PKCS12");
  privateKeyAlias = props.getProperty(PRIVATE_KEY_ALIAS_PROP);
  if (privateKeyAlias == null) {
   privateKeyAlias = "";
  }
  String keyStorePass = props.getProperty(PRIVATE_KEY_PASSWD_PROP);
  char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
  FileInputStream privateKeyFile = new FileInputStream(privateKeyFilePath);
  try {
   ks.load(privateKeyFile, passPhrase);
  } finally {
   privateKeyFile.close();
  }
  Key key = ks.getKey(privateKeyAlias, passPhrase);
  Certificate keyCert = ks.getCertificate(privateKeyAlias);
  if (key instanceof PrivateKey && keyCert instanceof X509Certificate) {
   privateKeyEncrypt = (PrivateKey) key;
   privateKeySignAlgo = ((X509Certificate) keyCert).getSigAlgName();
   privateKeySubject = ((X509Certificate) keyCert).getSubjectDN().getName();
  }
 }
}

代码示例来源:origin: apache/incubator-pinot

FileInputStream is = new FileInputStream(new File(_serverCACertFile));
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
int i = 0;
while (is.available() > 0) {
 X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
 LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
   cert.getIssuerDN().toString());

代码示例来源:origin: eclipse-vertx/vert.x

public KeyStoreHelper(KeyStore ks, String password) throws Exception {
 Enumeration<String> en = ks.aliases();
 while (en.hasMoreElements()) {
  String alias = en.nextElement();
  Certificate cert = ks.getCertificate(alias);
  if (ks.isCertificateEntry(alias) && ! alias.startsWith(DUMMY_CERT_ALIAS)){
   final KeyStore keyStore = createEmptyKeyStore();
   keyStore.setCertificateEntry("cert-1", cert);
  if (ks.isKeyEntry(alias) && cert instanceof X509Certificate) {
   X509Certificate x509Cert = (X509Certificate) cert;
   Collection<List<?>> ans = x509Cert.getSubjectAlternativeNames();
   List<String> domains = new ArrayList<>();
   if (ans != null) {
   String dn = x509Cert.getSubjectX500Principal().getName();
   domains.addAll(getX509CertificateCommonNames(dn));
   if (!domains.isEmpty()) {

代码示例来源:origin: wildfly/wildfly

@Override
public RealmIdentity getRealmIdentity(final Principal principal) throws RealmUnavailableException {
  if (principal instanceof NamePrincipal) {
    String name = principal.getName();
    log.tracef("KeyStoreRealm: obtaining certificate by alias [%s]", name);
    return new KeyStoreRealmIdentity(name);
      final KeyStore keyStore = this.keyStore;
      try {
        final Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
          final String alias = aliases.nextElement();
          if (keyStore.isCertificateEntry(alias)) {
            final Certificate certificate = keyStore.getCertificate(alias);
            if (certificate instanceof X509Certificate && x500Principal.equals(X500PrincipalUtil.asX500Principal(((X509Certificate) certificate).getSubjectX500Principal()))) {
              log.tracef("KeyStoreRealm: certificate found by X500Principal in alias [%s]", alias);
              return new KeyStoreRealmIdentity(alias);

代码示例来源:origin: oracle/helidon

static List<X509Certificate> loadCertificates(KeyStore keyStore) {
    List<X509Certificate> certs = new LinkedList<>();
    try {
      Enumeration<String> aliases = keyStore.aliases();
      while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isCertificateEntry(alias)) {
          X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
          certs.add(cert);

          LOGGER.finest(() -> "Added certificate under alis " + alias + " for " + cert
              .getSubjectDN() + " to list of certificates");
        }
      }
    } catch (KeyStoreException e) {
      throw new PkiException("Failed to load certificates from keystore: " + keyStore, e);
    }

    return certs;
  }
}

代码示例来源:origin: fabric8io/kubernetes-client

public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
  CertificateFactory certFactory = CertificateFactory.getInstance("X509");
  X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);
  byte[] keyBytes = decodePem(keyInputStream);
  PrivateKey privateKey;
  KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
  try {
   // First let's try PKCS8
   privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
  } catch (InvalidKeySpecException e) {
   // Otherwise try PKCS8
   RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes);
   privateKey = keyFactory.generatePrivate(keySpec);
  }
  KeyStore keyStore = KeyStore.getInstance("JKS");
  if (Utils.isNotNullOrEmpty(keyStoreFile)){
   keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
  } else {
   loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
  }
  String alias = cert.getSubjectX500Principal().getName();
  keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[]{cert});
  return keyStore;
}

代码示例来源:origin: rhuss/jolokia

/**
 * Update a keystore with a CA certificate
 *
 * @param pTrustStore the keystore to update
 * @param pCaCert     CA cert as PEM used for the trust store
 */
public static void updateWithCaPem(KeyStore pTrustStore, File pCaCert)
    throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
  InputStream is = new FileInputStream(pCaCert);
  try {
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);
    String alias = cert.getSubjectX500Principal().getName();
    pTrustStore.setCertificateEntry(alias, cert);
  } finally {
    is.close();
  }
}

代码示例来源:origin: robovm/robovm

/**
 * Returns the {@code issuer} (issuer distinguished name) as an {@code
 * X500Principal}.
 *
 * @return the {@code issuer} (issuer distinguished name).
 */
public X500Principal getIssuerX500Principal() {
  try {
    // TODO if there is no X.509 certificate provider installed
    // should we try to access Harmony X509CertImpl via classForName?
    CertificateFactory factory = CertificateFactory
        .getInstance("X.509");
    X509Certificate cert = (X509Certificate) factory
        .generateCertificate(new ByteArrayInputStream(getEncoded()));
    return cert.getIssuerX500Principal();
  } catch (Exception e) {
    throw new RuntimeException("Failed to get X500Principal issuer", e);
  }
}

代码示例来源:origin: stackoverflow.com

InputStream certStream = new ByteArrayInputStream(rawCert);
  CertificateFactory certFactory = CertificateFactory.getInstance("X509");
  X509Certificate x509Cert = (X509Certificate) certFactory.generateCertificate(certStream);
  sb.append("Certificate subject: " + x509Cert.getSubjectDN() + "<br>");
  sb.append("Certificate issuer: " + x509Cert.getIssuerDN() + "<br>");
  sb.append("Certificate serial number: " + x509Cert.getSerialNumber() + "<br>");
  sb.append("<br>");

代码示例来源:origin: stackoverflow.com

private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
private boolean isDebuggable(Context ctx)
    Signature signatures[] = pinfo.signatures;
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
      ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
      X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);       
      debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
      if (debuggable)
        break;

相关文章