下面列出了java.security.KeyStore#getInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
void testAuthenticateKeystoreECWebsite() throws Exception {
final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(getClass().getResourceAsStream("/keystore.jks"), "password".toCharArray());
final Key privateKey = ks.getKey("trellis-ec", "password".toCharArray());
final String token = Jwts.builder().setSubject("acoburn")
.claim("website", "https://people.apache.org/~acoburn/#i")
.signWith(privateKey, SignatureAlgorithm.ES256).compact();
final Authenticator authenticator = new JwtAuthenticator(
ks.getCertificate("trellis-ec").getPublicKey());
final Principal p = authenticator.authenticate(token);
assertNotNull(p, "Missing principal!");
assertEquals("https://people.apache.org/~acoburn/#i", p.getName(), "Incorrect webid!");
}
public static void useCaCertificateValidation(String certificatePath) {
try (InputStream is = new FileInputStream(certificatePath)) {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
X509Certificate caCertificate = (X509Certificate) CertificateFactory.getInstance("X.509")
.generateCertificate(is);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
keyStore.setCertificateEntry("caCert", caCertificate);
trustManagerFactory.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustManagerFactory.getTrustManagers(), null);
SSLContext.setDefault(context);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/**
* Generate a keystore with a default password.
* @param pwd default keystore password
* @throws Exception if any error occurs.
*/
private static void generateKeyStore(final String pwd) throws Exception {
final byte[] passwordBytes = pwd.getBytes();
// encode the password in Base64
final byte[] encodedBytes = Base64Encoding.encodeBytesToBytes(passwordBytes);
// store the encoded password to a file
try (final FileOutputStream fos = new FileOutputStream(getPasswordFilename())) {
fos.write(encodedBytes);
fos.flush();
}
final char[] password = pwd.toCharArray();
final KeyStore ks = KeyStore.getInstance(getKeystoreProvider());
// create an empty keystore
ks.load(null, password);
// generate the initial secret key
final KeyGenerator gen = KeyGenerator.getInstance(getAlgorithm());
final SecretKey key = gen.generateKey();
// save the key in the keystore
final KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key);
ks.setEntry(getKeyAlias(), skEntry, new KeyStore.PasswordProtection(password));
// save the keystore to a file
try (final FileOutputStream fos = new FileOutputStream(getKeystoreFilename())) {
ks.store(fos, password);
}
}
public static void main(String[] args) throws Exception {
String FILE = "newsize7-ks";
new File(FILE).delete();
sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
FILE +
" -alias a -dname cn=c -storepass changeit" +
" -keypass changeit -keyalg rsa").split(" "));
KeyStore ks = KeyStore.getInstance("JKS");
try (FileInputStream fin = new FileInputStream(FILE)) {
ks.load(fin, null);
}
Files.delete(Paths.get(FILE));
RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
if (r.getModulus().bitLength() != 2048) {
throw new Exception("Bad keysize");
}
X509Certificate x = (X509Certificate)ks.getCertificate("a");
if (!x.getSigAlgName().equals("SHA256withRSA")) {
throw new Exception("Bad sigalg");
}
}
public boolean isPrivateKeyStore(byte[] content, String password, String type)
throws java.lang.Exception {
try {
boolean isPrivateStore = false;
ByteArrayInputStream stream = new ByteArrayInputStream(content);
KeyStore store = KeyStore.getInstance(type);
store.load(stream, password.toCharArray());
Enumeration<String> aliases = store.aliases();
while (aliases.hasMoreElements()) {
String value = aliases.nextElement();
if (store.isKeyEntry(value)) {
isPrivateStore = true;
break;
}
}
return isPrivateStore;
} catch (java.lang.Exception e) {
log.error("Error in checking private key store.", e);
throw e;
}
}
private static void run(String keyAlg, int keySize,
String expectedSigAlg, String sigAlg) throws Exception {
String alias = keyAlg + keySize + System.currentTimeMillis();
String cmd = "-keystore ks -storepass changeit" +
" -keypass changeit -alias " + alias +
" -keyalg " + keyAlg + " -keysize " + keySize +
" -genkeypair -dname CN=" + alias + " -debug";
if (sigAlg != null) {
cmd += " -sigalg " + sigAlg;
}
Main.main(cmd.split(" "));
KeyStore ks = KeyStore.getInstance(
new File("ks"), "changeit".toCharArray());
X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
String actualSigAlg = cert.getSigAlgName();
if (!actualSigAlg.equals(expectedSigAlg)) {
throw new Exception("Failure at " + alias + ": expected "
+ expectedSigAlg + ", actually " + actualSigAlg);
}
}
private static KeyManagerFactory getKeyManagerFactory(InputStream key, String keyPassword) {
KeyManagerFactory kmf = null;
try {
String keyStoreType = "BKS";
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(key, keyPassword.toCharArray());
String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
kmf.init(keyStore, keyPassword.toCharArray());
} catch (Exception e) {
e.printStackTrace();
}
return kmf;
}
public static void main(String[] args) throws Exception {
String FILE = "newsize7-ks";
new File(FILE).delete();
sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
FILE +
" -alias a -dname cn=c -storepass changeit" +
" -keypass changeit -keyalg rsa").split(" "));
KeyStore ks = KeyStore.getInstance("JKS");
try (FileInputStream fin = new FileInputStream(FILE)) {
ks.load(fin, null);
}
Files.delete(Paths.get(FILE));
RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
if (r.getModulus().bitLength() != 2048) {
throw new Exception("Bad keysize");
}
X509Certificate x = (X509Certificate)ks.getCertificate("a");
if (!x.getSigAlgName().equals("SHA256withRSA")) {
throw new Exception("Bad sigalg");
}
}
private void storeAttrs() throws UnrecoverableEntryException,
GeneralSecurityException, NoSuchAlgorithmException,
KeyStoreException, IOException {
KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
Utils.KeyStoreType.pkcs12, PASSWORD);
KeyStore ksAttr = KeyStore
.getInstance(Utils.KeyStoreType.pkcs12.name());
ksAttr.load(null);
Key key = ksIn.getKey(ALIAS, PASSWORD);
Certificate cert = ksIn.getCertificate(ALIAS);
Set<KeyStore.Entry.Attribute> attrs =
new HashSet<>(Arrays.asList(ATTR_SET));
KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
new Certificate[]{cert}, attrs);
ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
KEY_PASSWORD));
out.println("Attributes before store:");
e.getAttributes().stream().forEach((attr) -> {
out.println(attr.getName() + ", '" + attr.getValue() + "'");
});
Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
+ KESTORE_NEW, PASSWORD);
}
/**
* Create a KeyStore from standard PEM files.
* @param privateKeyPem the private key PEM file
* @param certificatePem the certificate(s) PEM file
* @param password to set to protect the private key
*/
public static KeyStore createKeyStore(InputStream certificatePem, InputStream privateKeyPem, final String password) throws Exception {
final X509Certificate[] cert = createCertificates(certificatePem);
final KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
// Import private key
PEMKeyPair pem = CertUtils.getPEM(privateKeyPem);
boolean isGM = pem.getPrivateKeyInfo().getPrivateKeyAlgorithm().getParameters().toString().equals(SM2Priv.SM2OID);
final PrivateKey key = CertUtils.getPrivateKeyFromPEM(pem, isGM);
keystore.setKeyEntry("tlsCertPriv", key, password.toCharArray(), cert);
return keystore;
}
private static KeyManagerFactory getKeyManagerFactory(
Configuration config,
boolean internal,
SslProvider provider)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
UnrecoverableKeyException {
String keystoreFilePath = getAndCheckOption(
config,
internal ? SecurityOptions.SSL_INTERNAL_KEYSTORE : SecurityOptions.SSL_REST_KEYSTORE,
SecurityOptions.SSL_KEYSTORE);
String keystorePassword = getAndCheckOption(
config,
internal ? SecurityOptions.SSL_INTERNAL_KEYSTORE_PASSWORD : SecurityOptions.SSL_REST_KEYSTORE_PASSWORD,
SecurityOptions.SSL_KEYSTORE_PASSWORD);
String certPassword = getAndCheckOption(
config,
internal ? SecurityOptions.SSL_INTERNAL_KEY_PASSWORD : SecurityOptions.SSL_REST_KEY_PASSWORD,
SecurityOptions.SSL_KEY_PASSWORD);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream keyStoreFile = Files.newInputStream(new File(keystoreFilePath).toPath())) {
keyStore.load(keyStoreFile, keystorePassword.toCharArray());
}
final KeyManagerFactory kmf;
if (provider == OPENSSL || provider == OPENSSL_REFCNT) {
kmf = new OpenSslX509KeyManagerFactory();
} else {
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
}
kmf.init(keyStore, certPassword.toCharArray());
return kmf;
}
/**
* Loads a keystore from a base64-encoded String. Returns the KeyManager[]
* for the result.
*/
private KeyManager[] getKeyManagers(String keys) throws Exception {
byte[] bytes = Base64.decode(keys.getBytes());
InputStream inputStream = new ByteArrayInputStream(bytes);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(inputStream, PASSWORD.toCharArray());
inputStream.close();
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
return keyManagerFactory.getKeyManagers();
}
/**
* Load keystore information
* @param keyStoreName The keystore to read
* @param keyStorePwd Keystore password
* @return Keystore keystore object
* @throws Exception
*/
public static KeyStore loadKeyStore(String keyStoreName, String keyStorePwd) throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORETYPE);
// get user password and file input stream
char[] password = keyStorePwd.toCharArray();
java.io.FileInputStream fis = new java.io.FileInputStream(keyStoreName);
ks.load(fis, password);
fis.close();
return ks;
}
/**
* Returns the cacerts keystore with the configured CA certificates.
*/
public static KeyStore getCacertsKeyStore() throws Exception {
File file = new File(getCacerts());
if (!file.exists()) {
return null;
}
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
try (FileInputStream fis = new FileInputStream(file)) {
ks.load(fis, null);
}
return ks;
}
private static int signAlias(int testnum, String alias) throws Exception {
if (ks == null) {
ks = KeyStore.getInstance(KS_TYPE, provider);
ks.load(null, tokenPwd);
}
if (alias == null) {
Enumeration enu = ks.aliases();
if (enu.hasMoreElements()) {
alias = (String)enu.nextElement();
}
}
PrivateKey pkey = (PrivateKey)ks.getKey(alias, null);
if ("RSA".equals(pkey.getAlgorithm())) {
System.out.println("got [" + alias + "] signing key: " + pkey);
} else {
throw new SecurityException
("expected RSA, got " + pkey.getAlgorithm());
}
Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
s.initSign(pkey);
System.out.println("initialized signature object with key");
s.update("hello".getBytes());
System.out.println("signature object updated with [hello] bytes");
byte[] signed = s.sign();
System.out.println("received signature " + signed.length +
" bytes in length");
Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
v.initVerify(ks.getCertificate(alias));
v.update("hello".getBytes());
v.verify(signed);
System.out.println("signature verified");
System.out.println("test " + testnum++ + " passed");
return testnum;
}
public static KeyStore createRootCertificate(Authority authority,
String keyStoreType) throws NoSuchAlgorithmException,
NoSuchProviderException, IOException,
OperatorCreationException, CertificateException, KeyStoreException {
KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);
X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
nameBuilder.addRDN(BCStyle.CN, authority.commonName());
nameBuilder.addRDN(BCStyle.O, authority.organization());
nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());
X500Name issuer = nameBuilder.build();
BigInteger serial = BigInteger.valueOf(initRandomSerial());
X500Name subject = issuer;
PublicKey pubKey = keyPair.getPublic();
X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);
generator.addExtension(Extension.subjectKeyIdentifier, false,
createSubjectKeyIdentifier(pubKey));
generator.addExtension(Extension.basicConstraints, true,
new BasicConstraints(true));
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
| KeyUsage.digitalSignature | KeyUsage.keyEncipherment
| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
generator.addExtension(Extension.keyUsage, false, usage);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
generator.addExtension(Extension.extendedKeyUsage, false,
new DERSequence(purposes));
X509Certificate cert = signCertificate(generator, keyPair.getPrivate());
KeyStore result = KeyStore
.getInstance(keyStoreType/* , PROVIDER_NAME */);
result.load(null, null);
result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
authority.password(), new Certificate[] { cert });
return result;
}
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;
}
public static KeyStore loadJKSKeyStore(String classPath, String password) throws Exception {
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream is = SystemUtils.class.getClassLoader().getResourceAsStream(classPath);
keyStore.load(is, password.toCharArray());
return keyStore;
}
private static void checkKeystore(Properties props)
throws IOException, GeneralSecurityException {
if (log.isDebugOn())
log.debug("checkKeystore","Checking Keystore configuration");
final String keyStore =
System.getProperty(PropertyNames.KEYSTORE);
if (keyStore == null)
throw new IllegalArgumentException("System property " +
PropertyNames.KEYSTORE +
" not specified");
final String keyStorePass =
System.getProperty(PropertyNames.KEYSTORE_PASSWD);
if (keyStorePass == null) {
// We don't have the password, we can only check whether the
// file exists...
//
final File ksf = new File(keyStore);
if (! ksf.canRead())
throw new IOException(keyStore + ": not readable");
if (log.isDebugOn())
log.debug("checkSSL", "No password.");
throw new IllegalArgumentException("System property " +
PropertyNames.KEYSTORE_PASSWD +
" not specified");
}
// Now we're going to load the keyStore - just to check it's
// correct.
//
final String keyStoreType =
System.getProperty(PropertyNames.KEYSTORE_TYPE,
KeyStore.getDefaultType());
final KeyStore ks = KeyStore.getInstance(keyStoreType);
final FileInputStream fin = new FileInputStream(keyStore);
final char keypassword[] = keyStorePass.toCharArray();
try {
ks.load(fin,keypassword);
} finally {
Arrays.fill(keypassword,' ');
fin.close();
}
if (log.isDebugOn())
log.debug("checkSSL","SSL configuration successfully checked");
}
private static void checkKeystore(Properties props)
throws IOException, GeneralSecurityException {
if (log.isDebugOn())
log.debug("checkKeystore","Checking Keystore configuration");
final String keyStore =
System.getProperty(PropertyNames.KEYSTORE);
if (keyStore == null)
throw new IllegalArgumentException("System property " +
PropertyNames.KEYSTORE +
" not specified");
final String keyStorePass =
System.getProperty(PropertyNames.KEYSTORE_PASSWD);
if (keyStorePass == null) {
// We don't have the password, we can only check whether the
// file exists...
//
final File ksf = new File(keyStore);
if (! ksf.canRead())
throw new IOException(keyStore + ": not readable");
if (log.isDebugOn())
log.debug("checkSSL", "No password.");
throw new IllegalArgumentException("System property " +
PropertyNames.KEYSTORE_PASSWD +
" not specified");
}
// Now we're going to load the keyStore - just to check it's
// correct.
//
final String keyStoreType =
System.getProperty(PropertyNames.KEYSTORE_TYPE,
KeyStore.getDefaultType());
final KeyStore ks = KeyStore.getInstance(keyStoreType);
final FileInputStream fin = new FileInputStream(keyStore);
final char keypassword[] = keyStorePass.toCharArray();
try {
ks.load(fin,keypassword);
} finally {
Arrays.fill(keypassword,' ');
fin.close();
}
if (log.isDebugOn())
log.debug("checkSSL","SSL configuration successfully checked");
}