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

x33g5p2x  于2022-01-18 转载在 其他  
字(11.8k)|赞(0)|评价(0)|浏览(338)

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

Certificate介绍

[英]Abstract class to represent identity certificates. It represents a way to verify the binding of a Principal and its public key. Examples are X.509, PGP, and SDSI.
[中]抽象类来表示身份证书。它表示一种验证主体及其公钥绑定的方法。例如X.509、PGP和SDSI。

代码示例

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

CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(publicKeyBytes));
PublicKey publicKey = certificate.getPublicKey();
try (FileInputStream in = new FileInputStream(file);
  FileChannel channel = in.getChannel()) {
 ByteArrayOutputStream out = new ByteArrayOutputStream();
 channel.transferTo(0, channel.size(), Channels.newChannel(out));

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

private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
 if (log.isInfoEnabled()) {
  log.info("Loaded cluster key store from: {}", ksLocation);
  try {
   for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
    String alias = e.nextElement();
    Key key = ks.getKey(alias, ksPwd);
    Certificate[] certs = ks.getCertificateChain(alias);
    log.debug("{} -> {}", alias, certs);
    final byte[] encodedKey;
    if (certs != null && certs.length > 0) {
     encodedKey = certs[0].getEncoded();
    } else {
     log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
     encodedKey = key.getEncoded();
    }
    // Compute the certificate's fingerprint (use the key if certificate cannot be found)
    MessageDigest digest = MessageDigest.getInstance("SHA1");
    digest.update(encodedKey);
    StringJoiner fingerprint = new StringJoiner(":");
    for (byte b : digest.digest()) {
     fingerprint.add(String.format("%02X", b));
    }
    log.info("{} -> {}", alias, fingerprint);
   }
  } catch (Exception e) {
   log.warn("Unable to print contents of key store: {}", ksLocation, e);
  }
 }
}

代码示例来源:origin: JZ-Darkal/AndroidHttpCapture

Enumeration<String> aliases = trustStore.aliases();
List<String> keyStoreAliases = Collections.list(aliases);
  if (trustStore.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) {
    Certificate certificate = trustStore.getCertificate(alias);
    if (!(certificate instanceof X509Certificate)) {
      log.debug("Skipping non-X509Certificate in KeyStore. Certificate type: {}", certificate.getType());
      continue;

代码示例来源:origin: skylot/jadx

public String generateText() {
  StringBuilder str = new StringBuilder();
  String type = cert.getType();
  if (type.equals(CERTIFICATE_TYPE_NAME)) {
    str.append(generateTextForX509());
  } else {
    str.append(cert.toString());
  }
  return str.toString();
}

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

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;
  }
}

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

/**
 * Returns an alternate object to be serialized.
 *
 * @return the object to serialize.
 * @throws ObjectStreamException
 *             if the creation of the alternate object fails.
 */
protected Object writeReplace() throws ObjectStreamException {
  try {
    return new CertificateRep(getType(), getEncoded());
  } catch (CertificateEncodingException e) {
    throw new NotSerializableException("Could not create serialization object: " + e);
  }
}

代码示例来源:origin: org.springframework.ws/spring-ws-security

protected X509Certificate getCertificateFromTrustStore(String issuerName, BigInteger serialNumber)
    throws IOException {
  try {
    Enumeration<String> aliases = trustStore.aliases();
    while (aliases.hasMoreElements()) {
      String alias = aliases.nextElement();
      Certificate cert = trustStore.getCertificate(alias);
      if (cert == null || !X_509_CERTIFICATE_TYPE.equals(cert.getType())) {
        continue;
      }
      X509Certificate x509Cert = (X509Certificate) cert;
      String thisIssuerName = RFC2253Parser.normalize(x509Cert.getIssuerDN().getName());
      BigInteger thisSerialNumber = x509Cert.getSerialNumber();
      if (thisIssuerName.equals(issuerName) && thisSerialNumber.equals(serialNumber)) {
        return x509Cert;
      }
    }
  }
  catch (GeneralSecurityException e) {
    throw new IOException(e.getMessage());
  }
  return null;
}

代码示例来源:origin: org.eclipse/osgi

private Certificate findAlternativeRoot(X509Certificate cert, KeyStore store) throws InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, CertificateException {
  synchronized (store) {
    for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
      Certificate nextCert = store.getCertificate(e.nextElement());
      if (nextCert instanceof X509Certificate && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) {
        cert.verify(nextCert.getPublicKey());
        return nextCert;
      }
    }
    return null;
  }
}

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

is = new FileInputStream(file);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "password";
keystore.load(is, password.toCharArray());
Enumeration enumeration = keystore.aliases();
while(enumeration.hasMoreElements()) {
  String alias = (String)enumeration.nextElement();
  System.out.println("alias name: " + alias);
  Certificate certificate = keystore.getCertificate(alias);
  System.out.println(certificate.toString());

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

KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(file), password.toCharArray());
Enumeration<String> enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
 String alias = enumeration.nextElement();
 Certificate certificate = ks.getCertificate(alias);
 RSAPublicKey pub = (RSAPublicKey) certificate.getPublicKey();
 System.out.println(pub.getModulus().toString(16));
 System.out.println(pub.getPublicExponent().toString(16));
}

代码示例来源:origin: sscarduzio/elasticsearch-readonlyrest-plugin

java.security.KeyStore ks = java.security.KeyStore.getInstance("JKS");
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
  ks.load(new FileInputStream(keystoreFile), finKeystoerPassBa);
 } catch (Exception e) {
  e.printStackTrace();
 if (ks.aliases().hasMoreElements()) {
  String inferredAlias = ks.aliases().nextElement();
  logger.info("ROR SSL: ssl.key_alias not configured, took first alias in keystore: " + inferredAlias);
  sslKeyAlias = inferredAlias;
for (Certificate c : cchain) {
 sb.append("-----BEGIN CERTIFICATE-----\n");
 sb.append(Base64.getEncoder().encodeToString(c.getEncoded()));
 sb.append("\n");
 sb.append("-----END CERTIFICATE-----\n");

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

try {
  Certificate cert = null;
  final ByteArrayInputStream bais = new ByteArrayInputStream(tmpkey.getBytes());
  final BufferedInputStream bis = new BufferedInputStream(bais);
  final CertificateFactory certfac = CertificateFactory.getInstance("X.509");
  while (bis.available() > 0) {
    cert = certfac.generateCertificate(bis);
  rsaPubKey = (RSAPublicKey) cert.getPublicKey();
} catch (final Exception ex) {
  LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_CANNOT_OBTAIN_PUBLIC_KEY(), ex);

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

KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(certificateFile), certificatePassword.toCharArray());
Key key = keystore.getKey(certName, certificatePassword.toCharArray());
Certificate cert = keystore.getCertificate(certName);
PublicKey publicKey = cert.getPublicKey();
KeyPair keys = new KeyPair(publicKey, (PrivateKey) key);

代码示例来源:origin: spring-projects/spring-ws

protected PrivateKey getPrivateKey(X509Certificate certificate) throws IOException {
  try {
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
      String alias = aliases.nextElement();
      if (!keyStore.isKeyEntry(alias)) {
        continue;
      }
      Certificate cert = keyStore.getCertificate(alias);
      if (cert != null && cert.equals(certificate)) {
        return (PrivateKey) keyStore.getKey(alias, privateKeyPassword);
      }
    }
  }
  catch (GeneralSecurityException e) {
    throw new IOException(e.getMessage());
  }
  return null;
}

代码示例来源:origin: org.eclipse.jetty/jetty-util

public static X509Certificate[] getCertChain(SSLSession sslSession)
{
  try
  {
    Certificate[] javaxCerts = sslSession.getPeerCertificates();
    if (javaxCerts == null || javaxCerts.length == 0)
      return null;
    int length = javaxCerts.length;
    X509Certificate[] javaCerts = new X509Certificate[length];
    java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
    for (int i = 0; i < length; i++)
    {
      byte bytes[] = javaxCerts[i].getEncoded();
      ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
      javaCerts[i] = (X509Certificate)cf.generateCertificate(stream);
    }
    return javaCerts;
  }
  catch (SSLPeerUnverifiedException pue)
  {
    return null;
  }
  catch (Exception e)
  {
    LOG.warn(Log.EXCEPTION, e);
    return null;
  }
}

代码示例来源:origin: alibaba/druid

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);
  }
}

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

keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream("C:\\my.keystore"), "mypass".toCharArray());
Key key = keyStore.getKey("myalias", "mypass".toCharArray());
if (key instanceof PrivateKey) {
  Certificate cert = keyStore.getCertificate("myalias");
  PublicKey pubKey = cert.getPublicKey();
  privKey = (PrivateKey)key;
}
byte[] toDecodeBytes = new BigInteger(encodeMessageHex, 16).toByteArray();
Cipher decCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
decCipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] decodeMessageBytes = decCipher.doFinal(toDecodeBytes);
String decodeMessageString = new String(decodeMessageBytes);

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

KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
int nBefore = keyStore.size();
    .setKeyType("RSA")
    .setKeySize(2048)
    .setSubject(new X500Principal("CN=test"))
    .setSerialNumber(BigInteger.ONE)
    .setStartDate(notBefore.getTime())
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();
  new CipherInputStream(new FileInputStream(encryptedDataFilePath),
    outCipher);
byte [] roundTrippedBytes = new byte[1000]; // TODO: dynamically resize as we get more data

代码示例来源:origin: i2p/i2p.i2p

try {
  MessageDigest md = SHA1.getInstance();
  for(Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
    String alias = e.nextElement();
    if (ks.isCertificateEntry(alias)) {
      Certificate c = ks.getCertificate(alias);
      if (c != null && (c instanceof X509Certificate)) {
        byte[] enc = c.getEncoded();
        if (enc != null) {
          byte[] h = md.digest(enc);
              BigInteger serial = xc.getSerialNumber();
              String cn = CertUtil.getIssuerValue(xc, "CN");
              String ou = CertUtil.getIssuerValue(xc, "OU");
                 "\" CN: \"" + cn +
                 "\" OU: \"" + ou +
                 "\" s/n: " + serial.toString(16), null);

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

InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
  X509Certificate cert = chain[i];
  System.out.println
      (" " + (i + 1) + " Subject " + cert.getSubjectDN());
  System.out.println("   Issuer  " + cert.getIssuerDN());
  sha1.update(cert.getEncoded());
  System.out.println("   sha1    " + toHexString(sha1.digest()));
  md5.update(cert.getEncoded());
  System.out.println("   md5     " + toHexString(md5.digest()));
  System.out.println();

相关文章