下面列出了java.security.KeyStore#load ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static TrustManager[] useTrustStore(InputStream in,
char[] password,
String format)
throws GeneralSecurityException,
IOException,
NullPointerException {
if (format == null) {
format=KeyStore.getDefaultType();
}
KeyStore store=KeyStore.getInstance(format);
try {
store.load(in, password);
}
finally {
in.close();
}
TrustManagerFactory tmf=
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(store);
return(tmf.getTrustManagers());
}
private static void check(String encodedBlob) throws Exception {
byte[] blob = new byte[encodedBlob.length() * 2];
for (int i = 0; i < blob.length; ) {
final char ch = encodedBlob.charAt(i / 2);
blob[i++] = (byte) (ch >> 8);
blob[i++] = (byte) ch;
}
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(new ByteArrayInputStream(blob), new char[0]);
if (!store.aliases().nextElement().equals("test"))
throw new Exception("test alias not found");
KeyStore.PrivateKeyEntry e =
(KeyStore.PrivateKeyEntry) store.getEntry("test",
new KeyStore.PasswordProtection(new char[0]));
X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
throw new Exception("invalid certificate subject DN");
RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
throw new Exception("invalid public exponent");
}
private static X509TrustManager getTrustManager() throws Exception {
// generate certificate from cert string
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// create a key store
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
// import the trusted cert
try (ByteArrayInputStream is =
new ByteArrayInputStream(trustedCertStr.getBytes())) {
Certificate trustedCert = cf.generateCertificate(is);
ks.setCertificateEntry("RSA Export Signer", trustedCert);
}
// create the trust manager
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
tmf.init(ks);
return (X509TrustManager)tmf.getTrustManagers()[0];
}
private NettySocketSslContext() {
String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
try {
//
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(SslKeyStore.asInputStream(), SslKeyStore.getKeyStorePassword());
// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keystore, SslKeyStore.getCertificatePassword());
// Initialize the SSLContext to work with our key managers.
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new Error("Failed to initialize the server-side SSLContext", e);
}
}
private static void check(String encodedBlob) throws Exception {
byte[] blob = new byte[encodedBlob.length() * 2];
for (int i = 0; i < blob.length; ) {
final char ch = encodedBlob.charAt(i / 2);
blob[i++] = (byte) (ch >> 8);
blob[i++] = (byte) ch;
}
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(new ByteArrayInputStream(blob), new char[0]);
if (!store.aliases().nextElement().equals("test"))
throw new Exception("test alias not found");
KeyStore.PrivateKeyEntry e =
(KeyStore.PrivateKeyEntry) store.getEntry("test",
new KeyStore.PasswordProtection(new char[0]));
X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
throw new Exception("invalid certificate subject DN");
RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
throw new Exception("invalid public exponent");
}
@Override
public Void run() {
File f = new File(System.getProperty("java.home"),
"lib/security/cacerts");
KeyStore cacerts;
try {
cacerts = KeyStore.getInstance("JKS");
try (FileInputStream fis = new FileInputStream(f)) {
cacerts.load(fis, null);
certs = new HashSet<>();
Enumeration<String> list = cacerts.aliases();
String alias;
while (list.hasMoreElements()) {
alias = list.nextElement();
// Check if this cert is labeled a trust anchor.
if (alias.contains(" [jdk")) {
X509Certificate cert = (X509Certificate) cacerts
.getCertificate(alias);
certs.add(X509CertImpl.getFingerprint(HASH, cert));
}
}
}
} catch (Exception e) {
if (debug != null) {
debug.println("Error parsing cacerts");
}
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
String keyFilename =
System.getProperty("test.src", "./") + "/" + pathToStores +
"/" + keyStoreFile;
String trustFilename =
System.getProperty("test.src", "./") + "/" + pathToStores +
"/" + trustStoreFile;
System.setProperty("javax.net.ssl.keyStore", keyFilename);
System.setProperty("javax.net.ssl.keyStorePassword", passwd);
System.setProperty("javax.net.ssl.trustStore", trustFilename);
System.setProperty("javax.net.ssl.trustStorePassword", passwd);
sslctx = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keyFilename), passwd.toCharArray());
kmf.init(ks, passwd.toCharArray());
sslctx.init(kmf.getKeyManagers(), null, null);
sslssf = (SSLServerSocketFactory) sslctx.getServerSocketFactory();
sslsf = (SSLSocketFactory) sslctx.getSocketFactory();
if (debug)
System.setProperty("javax.net.debug", "all");
/*
* Start the tests.
*/
new SSLCtxAccessToSessCtx();
}
@Override
public KeyStore load(InputStream inputstream, String password)
throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
KeyStore ksKeys = KeyStore.getInstance(KEY_STORE_TYPE);
try {
ksKeys.load(inputstream, password.toCharArray());
} finally {
inputstream.close();
}
return ksKeys;
}
static KeyStore loadKeyStore(String path, char[] pass) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (var stream = new BufferedInputStream(new FileInputStream(path))) {
keyStore.load(stream, pass);
}
return keyStore;
}
public static void main(String argv[]) throws Exception {
String osName = System.getProperty("os.name");
if (!osName.startsWith("Windows")) {
System.out.println("Not windows");
return;
}
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
CertAndKeyGen ckg = new CertAndKeyGen("RSA", "SHA1withRSA");
ckg.setRandom(new SecureRandom());
boolean see63 = false, see65 = false;
while (!see63 || !see65) {
ckg.generate(1024);
RSAPrivateCrtKey k = (RSAPrivateCrtKey) ckg.getPrivateKey();
int len = k.getPrimeExponentP().toByteArray().length;
if (len == 63 || len == 65) {
if (len == 63) {
if (see63) continue;
else see63 = true;
}
if (len == 65) {
if (see65) continue;
else see65 = true;
}
System.err.print(len);
ks.setKeyEntry("anything", k, null, new X509Certificate[]{
ckg.getSelfCertificate(new X500Name("CN=Me"), 1000)
});
}
System.err.print('.');
}
ks.store(null, null);
}
public IpcdServerTlsContext(Boolean useTls, String keystoreFilePath, String keystoreFilePassword, String keyPassword) {
this.useTls = useTls;
if (useTls) {
SSLContext serverContext = null;
try {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) { algorithm = "SunX509"; }
try {
KeyStore ks = KeyStore.getInstance("JKS");
//FileInputStream fin = new FileInputStream(keystoreFilePath);
ks.load(getKeyStoreInputStream(keystoreFilePath), keystoreFilePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, keyPassword.toCharArray());
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new Error("Failed to initialize the server-side SSLContext", e);
}
} catch (Exception ex) {
logger.error("Error initializing SslContextManager.", ex);
} finally {
_context = serverContext;
}
} else {
_context = null;
}
}
public static TrustManager[] createFor(TrustStore trustStore) {
try {
InputStream keyStoreInputStream = trustStore.getKeyStoreInputStream();
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(keyStoreInputStream, trustStore.getKeyStorePassword().toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
trustManagerFactory.init(keyStore);
return BlacklistingTrustManager.createFor(trustManagerFactory.getTrustManagers());
} catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
@Test
public void appendToTruststore() throws Exception {
// get self-signed cert
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "changeit";
keystore.load(SslCertificateTrusterTest.class.getResourceAsStream("/selfsigned.jks"), password.toCharArray());
X509Certificate selfsigned = (X509Certificate) keystore.getCertificate("mykey");
SslCertificateTruster.appendToTruststore(new X509Certificate[] { selfsigned });
// verify defaultTrustManager contains cert
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// this will initialize with the first valid keystore
// 1. javax.net.ssl.trustStore
// 2. jssecerts
// 3. cacerts
// see https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/sun/security/ssl/TrustManagerFactoryImpl.java#L130
trustManagerFactory.init((KeyStore) null);
X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
X509Certificate[] cacerts = defaultTrustManager.getAcceptedIssuers();
for (X509Certificate certificate : cacerts) {
if (certificate.getSubjectDN().equals(selfsigned.getSubjectDN())) {
return;
}
}
Assert.fail();
}
private SSLContext getSSLContext() throws Exception {
// generate certificate from cert string
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// create a key store
KeyStore ts = KeyStore.getInstance("JKS");
KeyStore ks = KeyStore.getInstance("JKS");
ts.load(null, null);
ks.load(null, null);
// import the trused cert
ByteArrayInputStream is =
new ByteArrayInputStream(trustedCertStr.getBytes());
Certificate trusedCert = cf.generateCertificate(is);
is.close();
ts.setCertificateEntry("rsa-trusted-2048", trusedCert);
// generate the private key.
String keySpecStr = targetPrivateKey;
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
Base64.getMimeDecoder().decode(keySpecStr));
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec);
Certificate[] chain = new Certificate[1];
chain[0] = trusedCert;
// import the key entry.
ks.setKeyEntry("rsa-key-2048", priKey, passphrase, chain);
// create SSL context
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ts);
SSLContext sslCtx = SSLContext.getInstance("TLSv1");
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslCtx;
}
private static Optional<SSLContext> buildSslContext(
Optional<File> keystorePath,
Optional<String> keystorePassword,
Optional<File> truststorePath,
Optional<String> truststorePassword)
{
if (keystorePath.isEmpty() && truststorePath.isEmpty()) {
return Optional.empty();
}
try {
// load KeyStore if configured and get KeyManagers
KeyStore keystore = null;
KeyManager[] keyManagers = null;
if (keystorePath.isPresent()) {
char[] keyManagerPassword;
try {
// attempt to read the key store as a PEM file
keystore = PemReader.loadKeyStore(keystorePath.get(), keystorePath.get(), keystorePassword);
// for PEM encoded keys, the password is used to decrypt the specific key (and does not protect the keystore itself)
keyManagerPassword = new char[0];
}
catch (IOException | GeneralSecurityException ignored) {
keyManagerPassword = keystorePassword.map(String::toCharArray).orElse(null);
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream in = new FileInputStream(keystorePath.get())) {
keystore.load(in, keyManagerPassword);
}
}
validateCertificates(keystore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, keyManagerPassword);
keyManagers = keyManagerFactory.getKeyManagers();
}
// load TrustStore if configured, otherwise use KeyStore
KeyStore truststore = keystore;
if (truststorePath.isPresent()) {
truststore = loadTrustStore(truststorePath.get(), truststorePassword);
}
// create TrustManagerFactory
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(truststore);
// get X509TrustManager
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new RuntimeException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
// create SSLContext
SSLContext result = SSLContext.getInstance("SSL");
result.init(keyManagers, trustManagers, null);
return Optional.of(result);
}
catch (GeneralSecurityException | IOException e) {
throw new PrestoException(CASSANDRA_SSL_INITIALIZATION_FAILURE, e);
}
}
private static SSLContext generateSSLContext(String trustedCertStr,
String keyCertStr, String keySpecStr) throws Exception {
// generate certificate from cert string
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// create a key store
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
// import the trused cert
Certificate trusedCert = null;
ByteArrayInputStream is = null;
if (trustedCertStr != null) {
is = new ByteArrayInputStream(trustedCertStr.getBytes());
trusedCert = cf.generateCertificate(is);
is.close();
ks.setCertificateEntry("DSA Export Signer", trusedCert);
}
if (keyCertStr != null) {
// generate the private key.
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
Base64.getMimeDecoder().decode(keySpecStr));
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPrivateKey priKey =
(DSAPrivateKey)kf.generatePrivate(priKeySpec);
// generate certificate chain
is = new ByteArrayInputStream(keyCertStr.getBytes());
Certificate keyCert = cf.generateCertificate(is);
is.close();
Certificate[] chain = null;
if (trusedCert != null) {
chain = new Certificate[2];
chain[0] = keyCert;
chain[1] = trusedCert;
} else {
chain = new Certificate[1];
chain[0] = keyCert;
}
// import the key entry.
ks.setKeyEntry("Whatever", priKey, passphrase, chain);
}
// create SSL context
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
tmf.init(ks);
SSLContext ctx = SSLContext.getInstance("TLS");
if (keyCertStr != null && !keyCertStr.isEmpty()) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
ks = null;
} else {
ctx.init(null, tmf.getTrustManagers(), null);
}
return ctx;
}
@Before
public void setUp() throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException
{
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStoreFile = JKS_FILE;
String trustStoreFile = JKS_FILE;
String passw = JKS_FILE_PASSWORD;
char[] passphrase = passw.toCharArray();
ks.load(new FileInputStream(keyStoreFile), passphrase);
ts.load(new FileInputStream(trustStoreFile), passphrase);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ts);
sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
clientNotifications = new LinkedList<String>();
serverNotifications = new LinkedList<String>();
sslClientSem = new Semaphore(0);
sslServerSem = new Semaphore(0);
sslClient = createSSL(CLIENT_TAG, true, clientNotifications, sslClientSem);
sslServer = createSSL(SERVER_TAG, false, serverNotifications, sslServerSem);
log("== Init SSL listeners");
clientListener = crateListener(CLIENT_TAG, sslServer, clientNotifications, sslClientSem);
serverListener = crateListener(SERVER_TAG, sslClient, serverNotifications, sslServerSem);
sslClient.setSSLListener(clientListener);
sslServer.setSSLListener(serverListener);
cleintIn1 = CharBuffer.wrap(HELLO_FROM_CLIENT_1);
serverIn1 = CharBuffer.wrap(HELLO_FROM_SERVER_1);
cleintIn2 = CharBuffer.wrap(HELLO_FROM_CLIENT_2);
serverIn2 = CharBuffer.wrap(HELLO_FROM_SERVER_2);
cleintIn3 = CharBuffer.wrap(HELLO_FROM_CLIENT_3);
}
private static void createKeyStoreFromPemKey(
String clientCert,
String clientPass,
KeyStore store ) throws Exception {
try {
// Load CA Chain file
// CertificateFactory cf = CertificateFactory.getInstance("X.509");
// X509Certificate cert = (X509Certificate) cf.generateCertificate(new FileInputStream(caCert));
store.load(null);
// Load client's public and private keys from PKCS12 certificate
KeyStore inputKeyStore = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(clientCert);
char[] nPassword = null;
if ( (clientPass == null) || "".equals(clientPass.trim())) {
nPassword = null;
} else {
nPassword = clientPass.toCharArray();
}
inputKeyStore.load(fis, nPassword);
fis.close();
store.load(null, ( (clientPass != null)
? clientPass.toCharArray()
: null));
Enumeration<String> en = inputKeyStore.aliases();
while (en.hasMoreElements()) { // we are reading just one certificate.
String keyAlias = en.nextElement();
if (inputKeyStore.isKeyEntry(keyAlias)) {
Key key = inputKeyStore.getKey(keyAlias, nPassword);
Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
store.setKeyEntry("outkey",
key,
( (clientPass != null)
? clientPass.toCharArray()
: null),
certChain);
}
}
} catch (Exception e) {
throw new RuntimeException("Error creating keystore from Pem key", e);
}
}
protected KeyStore loadKeyStore() throws GeneralSecurityException, IOException {
KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
keyStore.load(null);
return keyStore;
}
private static SSLContext getSSLContext(String trusedCertStr,
String keyCertStr, byte[] modulus,
byte[] privateExponent, char[] passphrase) throws Exception {
// generate certificate from cert string
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream is =
new ByteArrayInputStream(trusedCertStr.getBytes());
Certificate trusedCert = cf.generateCertificate(is);
is.close();
// create a key store
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
// import the trused cert
ks.setCertificateEntry("RSA Export Signer", trusedCert);
if (keyCertStr != null) {
// generate the private key.
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
new BigInteger(modulus),
new BigInteger(privateExponent));
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey priKey =
(RSAPrivateKey)kf.generatePrivate(priKeySpec);
// generate certificate chain
is = new ByteArrayInputStream(keyCertStr.getBytes());
Certificate keyCert = cf.generateCertificate(is);
is.close();
Certificate[] chain = new Certificate[2];
chain[0] = keyCert;
chain[1] = trusedCert;
// import the key entry.
ks.setKeyEntry("Whatever", priKey, passphrase, chain);
}
// create SSL context
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
SSLContext ctx = SSLContext.getInstance("TLS");
if (keyCertStr != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} else {
ctx.init(null, tmf.getTrustManagers(), null);
}
return ctx;
}