Java/Security/Certificate
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Adding a Certificate to a Key Store
- 2 Creating a Certification Path
- 3 Getting the Subject and Issuer Distinguished Names of an X509 Certificate
- 4 Importing a Certificate from a File
- 5 Listing the Most-Trusted Certificate Authorities (CA) in a Key Store
- 6 Retrieving a Certificate from a Key Store
- 7 Retrieving the Certification Path of an SSL Server
- 8 Signature Test
- 9 Specify the keystore of certificates using the javax.net.ssl.keyStore system property:
- 10 Validating a Certification Path using the most-trusted CAs in the JDK"s cacerts file.
Adding a Certificate to a Key Store
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
public class Main {
public static void main(String[] argv) throws Exception {
FileInputStream is = new FileInputStream("your.keystore");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "my-keystore-password".toCharArray());
String alias = "myalias";
char[] password = "password".toCharArray();
Certificate cert = keystore.getCertificate(alias);
File keystoreFile = new File("your.keystore");
// Load the keystore contents
FileInputStream in = new FileInputStream(keystoreFile);
keystore.load(in, password);
in.close();
// Add the certificate
keystore.setCertificateEntry(alias, cert);
// Save the new keystore contents
FileOutputStream out = new FileOutputStream(keystoreFile);
keystore.store(out, password);
out.close();
}
}
Creating a Certification Path
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
public class Main {
public static void main(String[] argv) throws Exception {
FileInputStream is = new FileInputStream("your.keystore");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "my-keystore-password".toCharArray());
String alias = "myalias";
Certificate cert = keystore.getCertificate(alias);
CertificateFactory certFact = CertificateFactory.getInstance("X.509");
CertPath path = certFact.generateCertPath(Arrays.asList(new Certificate[]{cert}));
}
}
Getting the Subject and Issuer Distinguished Names of an X509 Certificate
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
public class Main {
public static void main(String[] argv) throws Exception {
FileInputStream is = new FileInputStream("your.keystore");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "my-keystore-password".toCharArray());
Enumeration e = keystore.aliases();
for (; e.hasMoreElements();) {
String alias = (String) e.nextElement();
java.security.cert.Certificate cert = keystore.getCertificate(alias);
if (cert instanceof X509Certificate) {
X509Certificate x509cert = (X509Certificate) cert;
// Get subject
Principal principal = x509cert.getSubjectDN();
String subjectDn = principal.getName();
// Get issuer
principal = x509cert.getIssuerDN();
String issuerDn = principal.getName();
}
}
}
}
Importing a Certificate from a File
import java.io.File;
import java.io.FileInputStream;
import java.security.cert.CertificateFactory;
public class Main {
public static void main(String[] argv) throws Exception {
FileInputStream is = new FileInputStream(new File("your"));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
java.security.cert.Certificate cert = cf.generateCertificate(is);
}
}
Listing the Most-Trusted Certificate Authorities (CA) in a Key Store
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.Iterator;
public class Main {
public static void main(String[] argv) throws Exception {
String filename = System.getProperty("java.home")
+ "/lib/security/cacerts".replace("/", File.separatorChar);
FileInputStream is = new FileInputStream(filename);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "password";
keystore.load(is, password.toCharArray());
PKIXParameters params = new PKIXParameters(keystore);
Iterator it = params.getTrustAnchors().iterator();
for (; it.hasNext();) {
TrustAnchor ta = (TrustAnchor) it.next();
X509Certificate cert = ta.getTrustedCert();
System.out.println(cert.getSigAlgName());
}
}
}
Retrieving a Certificate from a Key Store
import java.io.FileInputStream;
import java.security.KeyStore;
public class Main {
public static void main(String[] argv) throws Exception {
FileInputStream is = new FileInputStream("your.keystore");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "my-keystore-password".toCharArray());
// Get certificate
java.security.cert.Certificate cert = keystore.getCertificate("myalias");
}
}
Retrieving the Certification Path of an SSL Server
import java.security.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class Main {
public static void main(String[] argv) throws Exception {
int port = 443;
String hostname = "hostname";
SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port);
socket.startHandshake();
// Retrieve the server"s certificate chain
Certificate[] serverCerts = socket.getSession().getPeerCertificates();
socket.close();
}
}
Signature Test
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
public class SignatureTest {
public static void main(String[] args) {
try {
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
SecureRandom secrand = new SecureRandom();
keygen.initialize(512, secrand);
KeyPair keys1 = keygen.generateKeyPair();
PublicKey pubkey1 = keys1.getPublic();
PrivateKey privkey1 = keys1.getPrivate();
KeyPair keys2 = keygen.generateKeyPair();
PublicKey pubkey2 = keys2.getPublic();
PrivateKey privkey2 = keys2.getPrivate();
Signature signalg = Signature.getInstance("DSA");
signalg.initSign(privkey1);
String message = "Pay authors a bonus of $20,000.";
signalg.update(message.getBytes());
byte[] signature = signalg.sign();
Signature verifyalg = Signature.getInstance("DSA");
verifyalg.initVerify(pubkey1);
verifyalg.update(message.getBytes());
if (!verifyalg.verify(signature))
System.out.print("not ");
System.out.println("signed with private key 1");
verifyalg.initVerify(pubkey2);
verifyalg.update(message.getBytes());
if (!verifyalg.verify(signature))
System.out.print("not ");
System.out.println("signed with private key 2");
} catch (Exception e) {
System.out.println("Error " + e);
}
}
}
Specify the keystore of certificates using the javax.net.ssl.keyStore system property:
java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456 MyServer
Validating a Certification Path using the most-trusted CAs in the JDK"s cacerts file.
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorResult;
import java.security.cert.PKIXCertPathValidatorResult;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
public class Main {
public static void main(String[] argv) throws Exception {
String filename = System.getProperty("java.home")
+ "/lib/security/cacerts".replace("/", File.separatorChar);
FileInputStream is = new FileInputStream(filename);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "password";
keystore.load(is, password.toCharArray());
PKIXParameters params = new PKIXParameters(keystore);
params.setRevocationEnabled(false);
CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator
.getDefaultType());
CertPath certPath = null;
CertPathValidatorResult result = certPathValidator.validate(certPath, params);
PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
TrustAnchor ta = pkixResult.getTrustAnchor();
X509Certificate cert = ta.getTrustedCert();
}
}