java.security.KeyStore.getKey()方法的使用及代码示例

x33g5p2x  于2022-01-23 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(290)

本文整理了Java中java.security.KeyStore.getKey()方法的一些代码示例,展示了KeyStore.getKey()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。KeyStore.getKey()方法的具体详情如下:
包路径:java.security.KeyStore
类名称:KeyStore
方法名:getKey

KeyStore.getKey介绍

[英]Returns the key with the given alias, using the password to recover the key from the store.
[中]返回具有给定别名的密钥,使用密码从存储恢复密钥。

代码示例

代码示例来源:origin: stackoverflow.com

KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(this.getClass().getClassLoader().getResourceAsStream("keyFile.p12"), p12Password.toCharArray());
PrivateKey key = (PrivateKey)keystore.getKey(keyAlias, p12Password.toCharArray());

代码示例来源:origin: googlesamples/android-FingerprintDialog

/**
 * Initialize the {@link Cipher} instance with the created key in the
 * {@link #createKey(String, boolean)} method.
 *
 * @param keyName the key name to init the cipher
 * @return {@code true} if initialization is successful, {@code false} if the lock screen has
 * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
 * the key was generated.
 */
private boolean initCipher(Cipher cipher, String keyName) {
  try {
    mKeyStore.load(null);
    SecretKey key = (SecretKey) mKeyStore.getKey(keyName, null);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return true;
  } catch (KeyPermanentlyInvalidatedException e) {
    return false;
  } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
      | NoSuchAlgorithmException | InvalidKeyException e) {
    throw new RuntimeException("Failed to init Cipher", e);
  }
}

代码示例来源:origin: stackoverflow.com

KeyStore ks = KeyStore.getInstance("jks");
/* Load the key store. */
...
char[] password = ...;
/* Save the private key. */
FileOutputStream kos = new FileOutputStream("tmpkey.der");
Key pvt = ks.getKey("your_alias", password);
kos.write(pvt.getEncoded());
kos.flush();
kos.close();
/* Save the certificate. */
FileOutputStream cos = new FileOutputStream("tmpcert.der");
Certificate pub = ks.getCertificate("your_alias");
cos.write(pub.getEncoded());
cos.flush();
cos.close();

代码示例来源:origin: Tencent/tinker

private String getSignatureAlgorithm() throws Exception {
  InputStream is = null;
  try {
    is = new BufferedInputStream(new FileInputStream(config.mSignatureFile));
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(is, config.mStorePass.toCharArray());
    Key key = keyStore.getKey(config.mStoreAlias, config.mKeyPass.toCharArray());
    String keyAlgorithm = key.getAlgorithm();
    String signatureAlgorithm;
    if (keyAlgorithm.equalsIgnoreCase("DSA")) {
      signatureAlgorithm = "SHA1withDSA";
    } else if (keyAlgorithm.equalsIgnoreCase("RSA")) {
      signatureAlgorithm = "SHA1withRSA";
    } else if (keyAlgorithm.equalsIgnoreCase("EC")) {
      signatureAlgorithm = "SHA1withECDSA";
    } else {
      throw new RuntimeException("private key is not a DSA or "
          + "RSA key");
    }
    return signatureAlgorithm;
  } finally {
    StreamUtil.closeQuietly(is);
  }
}

代码示例来源:origin: ukanth/afwall

@TargetApi(Build.VERSION_CODES.M)
private boolean cipherInit() {
  try {
    cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
  } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
    throw new RuntimeException("Failed to get Cipher", e);
  }
  try {
    keyStore.load(null);
    SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
        null);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return true;
  } catch (KeyPermanentlyInvalidatedException e) {
    return false;
  } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
    throw new RuntimeException("Failed to init Cipher", e);
  }
}

代码示例来源:origin: stackoverflow.com

httpTransport = GoogleNetHttpTransport.newTrustedTransport();

KeyStore keyStore = KeyStore.getInstance("PKCS12", "SunJSSE");
keyStore.load(getClass().getResourceAsStream("/ACCESS-KEYS/filename.p12"), "notasecret".toCharArray());
    PrivateKey key = (PrivateKey) keyStore.getKey("privatekey", "notasecret".toCharArray());

credential = new GoogleCredential.Builder().setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)      
        .setServiceAccountScopes(Collections.singleton(BloggerScopes.BLOGGER))
        .setServiceAccountPrivateKey(key)
        .build();

代码示例来源:origin: spring-projects/spring-security-oauth

public KeyPair getKeyPair(String alias, char[] password) {
  try {
    synchronized (lock) {
      if (store == null) {
        synchronized (lock) {
          store = KeyStore.getInstance("jks");
          store.load(resource.getInputStream(), this.password);
        }
      }
    }
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password);
    RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
    return new KeyPair(publicKey, key);
  }
  catch (Exception e) {
    throw new IllegalStateException("Cannot load keys from store: " + resource, e);
  }
}

代码示例来源:origin: groupon/odo

private void reloadKeystore() throws FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException {
  InputStream is = new FileInputStream(new File(root, _caPrivateKeystore));
  if (is != null)	{
    _ks.load(is, _keystorepass);
    _caCert = (X509Certificate)_ks.getCertificate(_caCertAlias);
    _caPrivKey = (PrivateKey)_ks.getKey(_caPrivKeyAlias, _keypassword);
  }
}

代码示例来源:origin: apache/geode

/**
 * Load the private key of the server. This method is not thread safe.
 */
public static void initPrivateKey(Properties props) throws Exception {
 String privateKeyFilePath = props.getProperty(PRIVATE_KEY_FILE_PROP);
 privateKeyAlias = "";
 privateKeyEncrypt = null;
 if (privateKeyFilePath != null && privateKeyFilePath.length() > 0) {
  KeyStore ks = KeyStore.getInstance("PKCS12");
  privateKeyAlias = props.getProperty(PRIVATE_KEY_ALIAS_PROP);
  if (privateKeyAlias == null) {
   privateKeyAlias = "";
  }
  String keyStorePass = props.getProperty(PRIVATE_KEY_PASSWD_PROP);
  char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
  FileInputStream privateKeyFile = new FileInputStream(privateKeyFilePath);
  try {
   ks.load(privateKeyFile, passPhrase);
  } finally {
   privateKeyFile.close();
  }
  Key key = ks.getKey(privateKeyAlias, passPhrase);
  Certificate keyCert = ks.getCertificate(privateKeyAlias);
  if (key instanceof PrivateKey && keyCert instanceof X509Certificate) {
   privateKeyEncrypt = (PrivateKey) key;
   privateKeySignAlgo = ((X509Certificate) keyCert).getSigAlgName();
   privateKeySubject = ((X509Certificate) keyCert).getSubjectDN().getName();
  }
 }
}

代码示例来源:origin: benoberkfell/android-fingerprint-demo

private PrivateKey getPrivateKey() throws KeyPermanentlyInvalidatedException {
  try {
    KeyStore keyStore = getKeyStore();
    keyStore.load(null);
    return (PrivateKey) keyStore.getKey(KEY_NAME, null);
  } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
      | NoSuchAlgorithmException e) {
    throw new RuntimeException("failed to load private key from keystore", e);
  }
}

代码示例来源:origin: networknt/light-4j

/**
 * Get private key from java key store
 *
 * @param filename Key store file name
 * @param password Key store password
 * @param key key name in keystore
 * @return A PrivateKey object
 */
private static PrivateKey getPrivateKey(String filename, String password, String key) {
  if(logger.isDebugEnabled()) logger.debug("filename = " + filename + " key = " + key);
  PrivateKey privateKey = null;
  try {
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(Config.getInstance().getInputStreamFromFile(filename),
        password.toCharArray());
    privateKey = (PrivateKey) keystore.getKey(key,
        password.toCharArray());
  } catch (Exception e) {
    logger.error("Exception:", e);
  }
  if (privateKey == null) {
    logger.error("Failed to retrieve private key from keystore");
  }
  return privateKey;
}

代码示例来源:origin: eu.eu-emi.security/canl

protected void createSingleKeyView(KeyStore original, String alias, char[] password)
{
  try
  {
    ks = KeyStoreHelper.getInstanceForCredential("JKS");
    ks.load(null);
    Key key = original.getKey(alias, password);
    Certificate []chain = original.getCertificateChain(alias);
    ks.setKeyEntry(ALIAS, key, KEY_PASSWD, chain);
  } catch (Exception e)
  {
    throw new RuntimeException("Got error when loading data from the " +
        "correct original keystore - this is most probably a bug", e);
  }
}

代码示例来源:origin: wildfly/wildfly

@Override
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException {
  Attributes attributes = obtainAliasOrCertificateAttributes(alias, null, new String[]{keyAttribute});
  if (attributes == null) {
    log.tracef("Alias [%s] does not exist", alias);
    return null;
  }
  try {
    Attribute attribute = LdapUtil.getBinaryAttribute(attributes, keyAttribute);
    if (attribute == null) return null; // alias does not identify a key-related entry
    byte[] bytes = (byte[]) attribute.get();
    if (bytes == null) return null; // alias does not identify a key-related entry
    InputStream is = new ByteArrayInputStream(bytes);
    KeyStore keystore = KeyStore.getInstance(keyType);
    keystore.load(is, password);
    String firstAlias = keystore.aliases().nextElement();
    return keystore.getKey(firstAlias, password);
  } catch (KeyStoreException | CertificateException | IOException | NamingException e) {
    throw log.ldapKeyStoreFailedToRecoverKey(alias, e);
  }
}

代码示例来源:origin: apache/geode

final KeyStore ks = KeyStore.getInstance("PKCS12");
final char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
final FileInputStream certificatefile = new FileInputStream(keyStorePath);
 ks.load(certificatefile, passPhrase);
} finally {
 certificatefile.close();
final Key key = ks.getKey(alias, passPhrase);

代码示例来源:origin: apache/ignite

/** {@inheritDoc} */
@Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
  assertParameter(!F.isEmpty(keyStorePath), "KeyStorePath shouldn't be empty");
  assertParameter(keyStorePwd != null && keyStorePwd.length > 0,
    "KeyStorePassword shouldn't be empty");
  try (InputStream keyStoreFile = keyStoreFile()) {
    assertParameter(keyStoreFile != null, keyStorePath + " doesn't exists!");
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(keyStoreFile, keyStorePwd);
    if (log != null)
      log.info("Successfully load keyStore [path=" + keyStorePath + "]");
    masterKey = new KeystoreEncryptionKey(ks.getKey(masterKeyName, keyStorePwd), null);
  }
  catch (GeneralSecurityException | IOException e) {
    throw new IgniteSpiException(e);
  }
}

代码示例来源:origin: googleapis/google-cloud-java

@Override
Tuple<ServiceAccountCredentials, BlobInfo> parse(String... args)
  throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException,
    UnrecoverableKeyException {
 if (args.length != 4) {
  throw new IllegalArgumentException();
 }
 KeyStore keystore = KeyStore.getInstance("PKCS12");
 keystore.load(Files.newInputStream(Paths.get(args[0])), PASSWORD);
 PrivateKey privateKey = (PrivateKey) keystore.getKey("privatekey", PASSWORD);
 ServiceAccountCredentials credentials =
   ServiceAccountCredentials.newBuilder()
     .setClientEmail(args[1])
     .setPrivateKey(privateKey)
     .build();
 return Tuple.of(credentials, BlobInfo.newBuilder(BlobId.of(args[2], args[3])).build());
}

代码示例来源:origin: geoserver/geoserver

KeyStore oldKS = KeyStore.getInstance(KEYSTORETYPE);
try (InputStream fin = getResource().in()) {
  oldKS.load(fin, oldPassword);
KeyStore newKS = KeyStore.getInstance(KEYSTORETYPE);
newKS.load(null, newPassword);
KeyStore.PasswordProtection protectionparam =
    new KeyStore.PasswordProtection(newPassword);
while (enumeration.hasMoreElements()) {
  String alias = enumeration.nextElement();
  Key key = oldKS.getKey(alias, oldPassword);
  KeyStore.Entry entry = null;
  if (key instanceof SecretKey) entry = new KeyStore.SecretKeyEntry((SecretKey) key);

代码示例来源:origin: geoserver/geoserver

KeyStore newKS = KeyStore.getInstance(KEYSTORETYPE);
newKS.load(fin, passwd);
  newKS.getKey(enumeration.nextElement(), passwd);

代码示例来源:origin: stackoverflow.com

KeyStore ks = KeyStore.getInstance("JKS");
InputStream readStream = new FileInputStream(filePathToStore);
ks.load(readStream, keystorePasswordCharArray);
Key key = ks.getKey("keyAlias", passwordForKeyCharArray);
readStream.close();

代码示例来源:origin: stackoverflow.com

KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(certificateFile), certificatePassword.toCharArray());
Key key = keystore.getKey(certName, certificatePassword.toCharArray());
Certificate cert = keystore.getCertificate(certName);
PublicKey publicKey = cert.getPublicKey();
KeyPair keys = new KeyPair(publicKey, (PrivateKey) key);

相关文章