本文整理汇总了Java中java.security.KeyStore.store方法的典型用法代码示例。如果您正苦于以下问题:Java KeyStore.store方法的具体用法?Java KeyStore.store怎么用?Java KeyStore.store使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.security.KeyStore
的用法示例。
在下文中一共展示了KeyStore.store方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: addNewKey
import java.security.KeyStore; //导入方法依赖的package包/类
public static boolean addNewKey(KeyStore ks, File storeFile, char[] storePassword, DN dn) {
try {
Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn));
ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()});
FileOutputStream fos = new FileOutputStream(storeFile);
boolean threw = true;
try {
ks.store(fos, storePassword);
threw = false;
} finally {
Closeables.close(fos, threw);
}
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) {
return false;
}
return true;
}
示例2: createKey
import java.security.KeyStore; //导入方法依赖的package包/类
protected void createKey(String keyAlias)
{
KeyInfoManager keyInfoManager = null;
try
{
keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
Key key = getSecretKey(keyInfoManager.getKeyInformation(keyAlias));
encryptionKeysRegistry.registerKey(keyAlias, key);
keys.setKey(keyAlias, key);
KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);
ks.setKeyEntry(keyAlias, key, keyInfoManager.getKeyInformation(keyAlias).getPassword().toCharArray(), null);
OutputStream keyStoreOutStream = getKeyStoreOutStream();
ks.store(keyStoreOutStream, keyInfoManager.getKeyStorePassword().toCharArray());
// Workaround for MNT-15005
keyStoreOutStream.close();
logger.info("Created key: " + keyAlias + "\n in key store: \n" +
" Location: " + getKeyStoreParameters().getLocation() + "\n" +
" Provider: " + getKeyStoreParameters().getProvider() + "\n" +
" Type: " + getKeyStoreParameters().getType());
}
catch(Throwable e)
{
throw new AlfrescoRuntimeException(
"Failed to create key: " + keyAlias + "\n in key store: \n" +
" Location: " + getKeyStoreParameters().getLocation() + "\n" +
" Provider: " + getKeyStoreParameters().getProvider() + "\n" +
" Type: " + getKeyStoreParameters().getType(),
e);
}
finally
{
if(keyInfoManager != null)
{
keyInfoManager.clear();
}
}
}
示例3: storeCert
import java.security.KeyStore; //导入方法依赖的package包/类
public static void storeCert(X509Certificate cert, String filename, String password) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
filename = getActualTruststoreFilename(filename);
String alias = getThumbprint(cert, false);
if(password == null)
password = "changeit";
KeyStore ks = loadExtendedTrust(filename, password);
if(ks == null) {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, password.toCharArray());
}
ks.setCertificateEntry(alias, cert);
File f = new File(filename);
File dir = f.getParentFile();
if(dir !=null && !dir.exists())
dir.mkdirs();
OutputStream os = new FileOutputStream(filename);
try {
ks.store(os, password.toCharArray());
} finally {
os.close();
}
}
示例4: test
import java.security.KeyStore; //导入方法依赖的package包/类
private void test(Certificate certs[], String inKeyStorePath,
String userAlias, String outStorePass, String outKeyPass)
throws KeyStoreException, NoSuchProviderException, IOException,
CertificateException, UnrecoverableKeyException,
NoSuchAlgorithmException {
// init output key store
KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE");
outputKeyStore.load(null, null);
try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) {
// KeyStore have encoded by Base64.getMimeEncoder().encode(),need
// decode first.
byte[] input = Files.readAllBytes(Paths.get(CERT_PATH,
inKeyStorePath));
ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
.getMimeDecoder().decode(input));
// input key store
KeyStore inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE,
IN_KEYSTORE_PRV);
inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
// add key/certificate to output key store
Key key = inputKeyStore
.getKey(userAlias, IN_KEY_PASS.toCharArray());
out.println("Input Key Algorithm " + key.getAlgorithm());
out.println("====Input Certs=====");
if (certs == null) {
certs = new Certificate[] { inputKeyStore
.getCertificate(userAlias) };
}
for (Certificate cert : certs) {
out.println(((X509Certificate) cert).getSubjectDN());
}
outputKeyStore.setKeyEntry(userAlias, key,
outKeyPass.toCharArray(), certs);
Certificate retCerts[] = outputKeyStore
.getCertificateChain(userAlias);
out.println("====Output Certs=====");
for (Certificate retCert : retCerts) {
out.println(((X509Certificate) retCert).getSubjectDN());
}
out.println("====Output Key Algorithm=====");
Key outKey = outputKeyStore.getKey(userAlias,
outKeyPass.toCharArray());
out.println(outKey.getAlgorithm());
if (!key.equals(outKey)) {
throw new RuntimeException("key don't match");
}
if (!Arrays.equals(certs, retCerts)) {
throw new RuntimeException("certs don't match");
}
// save output
outputKeyStore.store(fout, outStorePass.toCharArray());
// test output
testKeyStore(outputKeyStore, outKeyPass.toCharArray());
}
}
示例5: saveKeyStore
import java.security.KeyStore; //导入方法依赖的package包/类
private static void saveKeyStore(KeyStore ks, String filename,
String password)
throws GeneralSecurityException, IOException {
FileOutputStream out = new FileOutputStream(filename);
try {
ks.store(out, password.toCharArray());
} finally {
out.close();
}
}
示例6: run
import java.security.KeyStore; //导入方法依赖的package包/类
private void run(String keystoreType) throws Exception {
char[] pw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(null, pw);
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey key = kg.generateKey();
KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
ks.setEntry(ALIAS, ske, kspp);
File ksFile = File.createTempFile("test", ".test");
try (FileOutputStream fos = new FileOutputStream(ksFile)) {
ks.store(fos, pw);
fos.flush();
}
// now see if we can get it back
try (FileInputStream fis = new FileInputStream(ksFile)) {
KeyStore ks2 = KeyStore.getInstance(keystoreType);
ks2.load(fis, pw);
KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
System.err.println("OK: worked just fine with " + keystoreType +
" keystore");
} else {
System.err.println("ERROR: keys are NOT equal after storing in "
+ keystoreType + " keystore");
}
}
}
示例7: testClientWithMutualAuthentication
import java.security.KeyStore; //导入方法依赖的package包/类
@Test
public void testClientWithMutualAuthentication() throws Exception {
Path tempFile = Files.createTempFile("keystore", ".jks");
try {
// ARRANGE
final String keystorePassword = "password";
connector = ImmutableConnector.builder().from(connector)
.keystorePath(tempFile.toString())
.keystorePassword(keystorePassword.getBytes(Charset.defaultCharset()))
.build();
// create a keystore
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null, keystorePassword.toCharArray());
// export the keystore to the temp file
OutputStream os = Files.newOutputStream(tempFile);
keystore.store(os, keystorePassword.toCharArray());
os.close();
// ACT
client = new AbstractRemoteClientImpl(connector, AbstractRemoteClientImpl.RetroService.class);
} finally {
Files.delete(tempFile);
}
}
示例8: generateIdentity
import java.security.KeyStore; //导入方法依赖的package包/类
private static P12KeyGenerationResult generateIdentity(KeyPairWithSubjectPublicKeyInfo kp,
KeystoreGenerationParameters params, String selfSignedCertSubject) throws Exception {
Date now = new Date();
Date notBefore = new Date(now.getTime() - 10 * MIN); // 10 minutes past
Date notAfter = new Date(notBefore.getTime() + 3650 * DAY);
String dnStr = (selfSignedCertSubject == null) ? "CN=DUMMY" : selfSignedCertSubject;
X500Name subjectDn = new X500Name(dnStr);
SubjectPublicKeyInfo subjectPublicKeyInfo = kp.subjectPublicKeyInfo();
ContentSigner contentSigner = getContentSigner(kp.kypair().getPrivate());
// Generate keystore
X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn,
BigInteger.valueOf(1), notBefore, notAfter, subjectDn, subjectPublicKeyInfo);
KeyAndCertPair identity = new KeyAndCertPair(certGenerator.build(contentSigner),
kp.kypair().getPrivate());
KeyStore ks = KeyUtil.getKeyStore("PKCS12");
ks.load(null, params.password());
ks.setKeyEntry("main", identity.key(), params.password(),
new Certificate[]{identity.jceCert()});
ByteArrayOutputStream ksStream = new ByteArrayOutputStream();
try {
ks.store(ksStream, params.password());
} finally {
ksStream.flush();
}
P12KeyGenerationResult result = new P12KeyGenerationResult(ksStream.toByteArray());
result.setKeystoreObject(ks);
return result;
}
示例9: execute0
import java.security.KeyStore; //导入方法依赖的package包/类
@Override
protected Object execute0() throws Exception {
File realKsFile = new File(IoUtil.expandFilepath(ksFile));
KeyStore ks = KeyStore.getInstance(ksType);
char[] password = readPasswordIfNotSet(ksPwd);
Set<String> aliases = new HashSet<>(10);
if (realKsFile.exists()) {
FileInputStream inStream = new FileInputStream(realKsFile);
try {
ks.load(inStream, password);
} finally {
inStream.close();
}
Enumeration<String> strs = ks.aliases();
while (strs.hasMoreElements()) {
aliases.add(strs.nextElement());
}
} else {
ks.load(null);
}
for (String certFile : certFiles) {
X509Certificate cert = X509Util.parseCert(certFile);
String baseAlias = X509Util.getCommonName(cert.getSubjectX500Principal());
String alias = baseAlias;
int idx = 2;
while (aliases.contains(alias)) {
alias = baseAlias + "-" + (idx++);
}
ks.setCertificateEntry(alias, cert);
aliases.add(alias);
}
ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
ks.store(bout, password);
saveVerbose("saved keystore to file", realKsFile, bout.toByteArray());
return null;
}
示例10: execute0
import java.security.KeyStore; //导入方法依赖的package包/类
@Override
protected Object execute0() throws Exception {
File realInFile = new File(IoUtil.expandFilepath(inFile));
File realOutFile = new File(IoUtil.expandFilepath(outFile));
if (CompareUtil.equalsObject(realInFile, realOutFile)) {
throw new IllegalCmdParamException("in and out cannot be the same");
}
KeyStore inKs = KeyStore.getInstance(inType);
KeyStore outKs = KeyStore.getInstance(outType);
outKs.load(null);
char[] inPassword = readPasswordIfNotSet("password of the source keystore", inPwd);
FileInputStream inStream = new FileInputStream(realInFile);
try {
inKs.load(inStream, inPassword);
} finally {
inStream.close();
}
char[] outPassword = readPasswordIfNotSet("password of the destination keystore", outPwd);
Enumeration<String> aliases = inKs.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (inKs.isKeyEntry(alias)) {
Certificate[] certs = inKs.getCertificateChain(alias);
Key key = inKs.getKey(alias, inPassword);
outKs.setKeyEntry(alias, key, outPassword, certs);
} else {
Certificate cert = inKs.getCertificate(alias);
outKs.setCertificateEntry(alias, cert);
}
}
ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
outKs.store(bout, outPassword);
saveVerbose("saved destination keystore to file", realOutFile, bout.toByteArray());
return null;
}
示例11: runTest
import java.security.KeyStore; //导入方法依赖的package包/类
public void runTest(Provider p) throws Exception {
try (FileOutputStream fos = new FileOutputStream("jceks");
FileInputStream fis = new FileInputStream("jceks");) {
KeyStore ks = KeyStore.getInstance("jceks", p);
// create an empty key store
ks.load(null, null);
// store the secret keys
String aliasHead = new String("secretKey");
for (int j = 0; j < NUM_ALGOS; j++) {
ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
}
// write the key store out to a file
ks.store(fos, PASSWDF);
// wipe clean the existing key store
for (int k = 0; k < NUM_ALGOS; k++) {
ks.deleteEntry(aliasHead + k);
}
if (ks.size() != 0) {
throw new RuntimeException("ERROR: re-initialization failed");
}
// reload the key store with the file
ks.load(fis, PASSWDF);
// check the integrity/validaty of the key store
Key temp = null;
String alias = null;
if (ks.size() != NUM_ALGOS) {
throw new RuntimeException("ERROR: wrong number of key"
+ " entries");
}
for (int m = 0; m < ks.size(); m++) {
alias = aliasHead + m;
temp = ks.getKey(alias, PASSWDK);
// compare the keys
if (!temp.equals(sks[m])) {
throw new RuntimeException("ERROR: key comparison (" + m
+ ") failed");
}
// check the type of key
if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
throw new RuntimeException("ERROR: type identification ("
+ m + ") failed");
}
}
}
}
示例12: createKeyStore
import java.security.KeyStore; //导入方法依赖的package包/类
protected void createKeyStore(KeyStoreParameters keyStoreParameters, KeyMap keys)
{
KeyInfoManager keyInfoManager = null;
try
{
if(!keyStoreExists(keyStoreParameters.getLocation()))
{
keyInfoManager = getKeyInfoManager(keyStoreParameters.getKeyMetaDataFileLocation());
KeyStore ks = initialiseKeyStore(keyStoreParameters.getType(), keyStoreParameters.getProvider());
String keyStorePassword = keyInfoManager.getKeyStorePassword();
if(keyStorePassword == null)
{
throw new AlfrescoRuntimeException("Key store password is null for keystore at location "
+ getKeyStoreParameters().getLocation()
+ ", key store meta data location" + getKeyMetaDataFileLocation());
}
for(String keyAlias : keys.getKeyAliases())
{
KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias);
Key key = keys.getKey(keyAlias);
if(key == null)
{
logger.warn("Key with alias " + keyAlias + " is null when creating keystore at location " + keyStoreParameters.getLocation());
}
else
{
ks.setKeyEntry(keyAlias, key, keyInfo.getPassword().toCharArray(), null);
}
}
// try
// {
// throw new Exception("Keystore creation: " + );
// }
// catch(Throwable e)
// {
// logger.debug(e.getMessage());
// e.printStackTrace();
// }
OutputStream keyStoreOutStream = getKeyStoreOutStream();
ks.store(keyStoreOutStream, keyStorePassword.toCharArray());
// Workaround for MNT-15005
keyStoreOutStream.close();
}
else
{
logger.warn("Can't create key store " + keyStoreParameters.getLocation() + ", already exists.");
}
}
catch(Throwable e)
{
throw new AlfrescoRuntimeException(
"Failed to create keystore: \n" +
" Location: " + keyStoreParameters.getLocation() + "\n" +
" Provider: " + keyStoreParameters.getProvider() + "\n" +
" Type: " + keyStoreParameters.getType(),
e);
}
finally
{
if(keyInfoManager != null)
{
keyInfoManager.clear();
}
}
}
示例13: createKeyStore
import java.security.KeyStore; //导入方法依赖的package包/类
/**
* Create keystore file
*
* @param cert the needed certificate for creating the keystore
* @param host the host name. If not null it is appended to keystore file name
* @param databaseName the database name. If not null it is appended to keystore file name
* @param keyStoreFullPath the full path where the keystore file will be located
* @param keyStoreType the type of the keystore file
* @param keyStorePassword the the password for the keystore
*
* TIP: if the keystoreFullPath, keyStoreType, keyStorePassword are empty we will set the default
*
* @return Properties object with the keyStore location, type and password
*/
public synchronized static Properties createKeyStore(
Certificate cert,
String host,
String databaseName,
String keyStoreFullPath,
String keyStoreType,
String keyStorePassword ) {
if (StringUtils.isNullOrEmpty(keyStoreType) && StringUtils.isNullOrEmpty(keyStorePassword)
&& StringUtils.isNullOrEmpty(keyStoreFullPath)) {
// all parameters are empty
keyStoreFullPath = System.getProperty("java.io.tmpdir") + "ats_TempKeyStore_" + host + "_"
+ databaseName + ".jks";
keyStorePassword = "password";
keyStoreType = "JKS";
} else if (StringUtils.isNullOrEmpty(keyStoreType) || StringUtils.isNullOrEmpty(keyStorePassword)
|| StringUtils.isNullOrEmpty(keyStoreFullPath)) {
// at least one parameter is empty
throw new IllegalArgumentException("All keystore parameters should be not be empty!");
}
Properties props = new Properties();
if (!availableKeyStores.contains(keyStoreFullPath)) {
try (FileOutputStream fos = new FileOutputStream(keyStoreFullPath)) {
KeyStore ks = KeyStore.getInstance(keyStoreType);
// create the keystore file
ks.load(null, keyStorePassword.toCharArray());
ks.setCertificateEntry("certificate", cert);
ks.store(fos, keyStorePassword.toCharArray());
fos.close();
} catch (Exception e) {
throw new RuntimeException("No keystore was created!", e);
}
availableKeyStores.add(keyStoreFullPath);
}
props.put(OracleKeys.KEY_STORE_FULL_PATH, keyStoreFullPath);
props.put(OracleKeys.KEY_STORE_TYPE, keyStoreType);
props.put(OracleKeys.KEY_STORE_PASSWORD, keyStorePassword);
return props;
}
示例14: main
import java.security.KeyStore; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
// Prepare a JKS keystore with many entries
new File(JKSFILE).delete();
for (int i=0; i<SIZE; i++) {
System.err.print(".");
String cmd = "-keystore " + JKSFILE
+ " -storepass changeit -keypass changeit -keyalg rsa "
+ "-genkeypair -alias p" + i + " -dname CN=" + i;
sun.security.tools.keytool.Main.main(cmd.split(" "));
}
// Prepare EncryptedPrivateKeyInfo parameters, copied from various
// places in PKCS12KeyStore.java
AlgorithmParameters algParams =
AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
AlgorithmId algid = new AlgorithmId(
new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);
PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
SecretKey skey = skFac.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
// Pre-calculated keys and certs and aliases
byte[][] keys = new byte[SIZE][];
Certificate[][] certChains = new Certificate[SIZE][];
String[] aliases = new String[SIZE];
// Reads from JKS keystore and pre-calculate
KeyStore ks = KeyStore.getInstance("jks");
try (FileInputStream fis = new FileInputStream(JKSFILE)) {
ks.load(fis, PASSWORD);
}
for (int i=0; i<SIZE; i++) {
aliases[i] = "p" + i;
byte[] enckey = cipher.doFinal(
ks.getKey(aliases[i], PASSWORD).getEncoded());
keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
certChains[i] = ks.getCertificateChain(aliases[i]);
}
// Write into PKCS12 keystore. Use this overloaded version of
// setKeyEntry() to be as fast as possible, so that they would
// have same localKeyId.
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(null, PASSWORD);
for (int i=0; i<SIZE; i++) {
p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
}
try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
p12.store(fos, PASSWORD);
}
// Check private keys still match certs
p12 = KeyStore.getInstance("pkcs12");
try (FileInputStream fis = new FileInputStream(P12FILE)) {
p12.load(fis, PASSWORD);
}
for (int i=0; i<SIZE; i++) {
String a = "p" + i;
X509Certificate x = (X509Certificate)p12.getCertificate(a);
X500Name name = (X500Name)x.getSubjectDN();
if (!name.getCommonName().equals(""+i)) {
throw new Exception(a + "'s cert is " + name);
}
}
}
示例15: main
import java.security.KeyStore; //导入方法依赖的package包/类
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);
}