下面列出了java.security.KeyStore#setKeyEntry ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Path createJksTrustStore(
final Path parentDir, final TlsCertificateDefinition certDef) {
try {
final List<X509Certificate> certsInDef = certDef.certificates();
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
final Certificate certificate = certsInDef.get(0);
ks.setCertificateEntry("clientCert", certificate);
final PrivateKey privKey = certDef.keys().get(0);
ks.setKeyEntry(
"client", privKey, certDef.getPassword().toCharArray(), new Certificate[] {certificate});
final Path tempKeystore = parentDir.resolve("keystore.jks");
try (final FileOutputStream output = new FileOutputStream(tempKeystore.toFile())) {
ks.store(output, certDef.getPassword().toCharArray());
}
return tempKeystore;
} catch (final Exception e) {
throw new RuntimeException("Failed to construct a JKS keystore.");
}
}
public static void main(String[] args) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream(
new File(System.getProperty("test.src"),
"../tools/jarsigner/JarSigning.keystore"));
ks.load(fis, "bbbbbb".toCharArray());
PrivateKey pk = (PrivateKey) ks.getKey("c", "bbbbbb".toCharArray());
Certificate cert = ks.getCertificate("c");
ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
ks.setKeyEntry("8143913", pk, null, new Certificate[]{cert});
ks.deleteEntry("8143913");
}
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);
}
private static KeyStore createFireflyKeyStore() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair fireflyKeys = keyPairGenerator.generateKeyPair();
PrivateKey fireflySigningKey = fireflyKeys.getPrivate();
PublicKey fireflyPublicKey = fireflyKeys.getPublic();
KeyStore fireflyKeyStore = loadKeyStore();
SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder()
.setDn(ROOT_DN)
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName("SHA1withRSA")
.addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647")
.build();
X509Certificate issuerCertificate = issuerSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
fireflyKeyStore.setCertificateEntry("ca", issuerCertificate);
X509Certificate fireflyCertificate = new X509CertificateBuilder()
.setIssuerDn(ROOT_DN)
.setSubjectDn(FIREFLY_DN)
.setSignatureAlgorithmName("SHA1withRSA")
.setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey())
.setPublicKey(fireflyPublicKey)
.setSerialNumber(new BigInteger("1"))
.addExtension(new BasicConstraintsExtension(false, false, -1))
.build();
fireflyKeyStore.setKeyEntry("firefly", fireflySigningKey, KEY_PASSWORD.toCharArray(), new X509Certificate[]{fireflyCertificate,issuerCertificate});
return fireflyKeyStore;
}
public void configureHttps(final HttpsURLConnection httpsConnection, final int remoteServerId, final int ourIndex)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
UnrecoverableKeyException, KeyManagementException {
// Configure SSL context
final SSLContext sslContext = SSLContext.getInstance(CommonConfiguration.TLS_VERSION);
// Create in-memory key store
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
final char[] password = "password".toCharArray();
keyStore.load(null, password);
// Add the CA certificate for the server
keyStore.setCertificateEntry("ca-" + remoteServerId, this.caCerts.get(remoteServerId - 1));
// Add certificate and private key for the server
final X509Certificate ourCaCert = caCerts.get(ourIndex - 1);
keyStore.setKeyEntry("host", this.privateKey, password, new X509Certificate[] { hostCert, ourCaCert });
// Make Key Manager Factory
final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, password);
// Setup the trust manager factory
final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keyStore);
// Initialize the context
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
// Get the socket factory from the context
httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
}
private static KeyStore createTestKeyStore(SelfSignedX509CertificateAndSigningKey rootSelfSignedX509CertificateAndSigningKey, SelfSignedX509CertificateAndSigningKey sallySelfSignedX509CertificateAndSigningKey) throws Exception {
KeyStore testKeyStore = loadKeyStore();
X509Certificate sallyCertificate = sallySelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
testKeyStore.setKeyEntry("ssmith", sallySelfSignedX509CertificateAndSigningKey.getSigningKey(), KEY_PASSWORD.toCharArray(), new X509Certificate[]{sallyCertificate});
X509Certificate rootCertificate = rootSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
testKeyStore.setKeyEntry("ca", rootSelfSignedX509CertificateAndSigningKey.getSigningKey(), KEY_PASSWORD.toCharArray(), new X509Certificate[]{rootCertificate});
return testKeyStore;
}
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);
}
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;
}
VaultSecret mapJks(VaultResponseData data, VaultJKSConfiguration jksConfiguration, VaultType type) throws SecretNotAccessibleException {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, getPassword(jksConfiguration).toCharArray());
Certificate[] publicKeyList = getPublicKey(data.getCertificate());
keyStore.setKeyEntry(
getAlias(jksConfiguration),
getPrivateKey(data.getPrivate_key()),
getPassword(jksConfiguration).toCharArray(),
publicKeyList);
if (jksConfiguration != null && !StringUtils.isEmpty(jksConfiguration.getCaAlias())) {
keyStore.setCertificateEntry(
jksConfiguration.getCaAlias(),
getPublicKey(data.getIssuing_ca())[0]
);
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
keyStore.store(outputStream, getPassword(jksConfiguration).toCharArray());
String b64KeyStore = Base64.getEncoder().encodeToString(outputStream.toByteArray());
HashMap<String, String> secretData = new HashMap<String, String>() {{
put(getKey(jksConfiguration), b64KeyStore);
}};
String compare;
if (type.equals(VaultType.CERTJKS)) {
String base64Cert = Base64.getEncoder().encodeToString(data.getCertificate().getBytes());
String base64Key = Base64.getEncoder().encodeToString(data.getPrivate_key().getBytes());
compare = Sha256.generateSha256(base64Cert, base64Key);
} else {
// VaultType.PKIJKS
X509Certificate compareCert = getCertificateWithShortestLivetime(publicKeyList);
SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
TimeZone tz = TimeZone.getTimeZone("UTC");
dateFormat.setTimeZone(tz);
compare = dateFormat.format(compareCert.getNotAfter());
}
return new VaultSecret(secretData, compare);
} catch (IOException | GeneralSecurityException e) {
throw new SecretNotAccessibleException("Couldn't generate keystore", e);
}
}
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 createServerCertificate(String commonName,
SubjectAlternativeNameHolder subjectAlternativeNames,
Authority authority, Certificate caCert, PrivateKey caPrivKey)
throws NoSuchAlgorithmException, NoSuchProviderException,
IOException, OperatorCreationException, CertificateException,
InvalidKeyException, SignatureException, KeyStoreException {
KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);
X500Name issuer = new X509CertificateHolder(caCert.getEncoded())
.getSubject();
BigInteger serial = BigInteger.valueOf(initRandomSerial());
X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
name.addRDN(BCStyle.CN, commonName);
name.addRDN(BCStyle.O, authority.certOrganisation());
name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
X500Name subject = name.build();
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());
builder.addExtension(Extension.subjectKeyIdentifier, false,
createSubjectKeyIdentifier(keyPair.getPublic()));
builder.addExtension(Extension.basicConstraints, false,
new BasicConstraints(false));
subjectAlternativeNames.fillInto(builder);
X509Certificate cert = signCertificate(builder, caPrivKey);
cert.checkValidity(new Date());
cert.verify(caCert.getPublicKey());
KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType()
/* , PROVIDER_NAME */);
result.load(null, null);
Certificate[] chain = { cert, caCert };
result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
authority.password(), chain);
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);
TrustManager tms[] = tmf.getTrustManagers();
if (tms == null || tms.length == 0) {
throw new Exception("unexpected trust manager implementation");
} else {
if (!(tms[0] instanceof X509ExtendedTrustManager)) {
throw new Exception("unexpected trust manager implementation: "
+ tms[0].getClass().getCanonicalName());
}
}
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;
}
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;
}
public KeyStore createKeyStore(String commonName, String[] domainNames) throws Exception {
/* シリアルナンバーの設定 */
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] hash = digest.digest(commonName.getBytes());
BigInteger templateSerial = new BigInteger(hash);
/* Subjectの設定 */
X500Name templateSubject = new X500Name(createSubject(commonName));
/* Builderの生成 */
X509v3CertificateBuilder serverBuilder = new X509v3CertificateBuilder(
templateIssuer,
templateSerial,
templateFrom,
templateTo,
templateSubject,
templatePubKey);
/* SANの設定 */
ArrayList<ASN1Encodable> sans = new ArrayList<>();
sans.add(new GeneralName(GeneralName.dNSName, createCNforSAN(commonName)));
for (String domainName : domainNames) {
//System.out.println(domainName);
sans.add(new GeneralName(GeneralName.dNSName, domainName));
}
DERSequence subjectAlternativeNames = new DERSequence(sans.toArray(new ASN1Encodable[sans.size()]));
serverBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames);
// 署名
X509CertificateHolder serverHolder = serverBuilder.build(createSigner());
/* 新しいKeyStoreを作成 */
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, password);
ks.setKeyEntry(
aliasServer,
keyPair.getPrivate(),
password,
new java.security.cert.Certificate[] {
certFactory.generateCertificate(new ByteArrayInputStream(serverHolder.getEncoded())),
certFactory.generateCertificate(new ByteArrayInputStream(caRootHolder.getEncoded()))
});
return ks;
}
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;
}
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;
}
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("RSA Export Signer", trusedCert);
}
if (keyCertStr != null) {
// generate the private key.
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
Base64.getMimeDecoder().decode(keySpecStr));
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();
// It's not allowed to send MD2 signed certificate to peer,
// even it may be a trusted certificate. Then we will not
// place the trusted certficate in the chain.
Certificate[] 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(tlsProtocol);
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;
}
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("RSA Export Signer", trusedCert);
}
if (keyCertStr != null) {
// generate the private key.
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
new BASE64Decoder().decodeBuffer(keySpecStr));
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 = 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;
}
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;
}
/**
* Creates a keystore with a single key and saves it to a file.
*
* @param filename String file to save
* @param password String store password to set on keystore
* @param keyPassword String key password to set on key
* @param alias String alias to use for the key
* @param privateKey Key to save in keystore
* @param cert Certificate to use as certificate chain associated to key
* @throws GeneralSecurityException for any error with the security APIs
* @throws IOException if there is an I/O error saving the file
*/
public static void createKeyStore(String filename,
Password password, Password keyPassword, String alias,
Key privateKey, Certificate cert) throws GeneralSecurityException, IOException {
KeyStore ks = createEmptyKeyStore();
ks.setKeyEntry(alias, privateKey, keyPassword.value().toCharArray(),
new Certificate[]{cert});
saveKeyStore(ks, filename, password);
}