当前位置: 首页>>代码示例>>Java>>正文


Java KeyStore.getKey方法代码示例

本文整理汇总了Java中java.security.KeyStore.getKey方法的典型用法代码示例。如果您正苦于以下问题:Java KeyStore.getKey方法的具体用法?Java KeyStore.getKey怎么用?Java KeyStore.getKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.security.KeyStore的用法示例。


在下文中一共展示了KeyStore.getKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: signWithJarSignerAPI

import java.security.KeyStore; //导入方法依赖的package包/类
private static void signWithJarSignerAPI(String jarName)
        throws Throwable {
    // Get JarSigner
    try (FileInputStream fis = new FileInputStream(KEYSTORE)) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(fis, STOREPASS.toCharArray());
            PrivateKey pk = (PrivateKey)ks.getKey(ALIAS, KEYPASS.toCharArray());
            Certificate cert = ks.getCertificate(ALIAS);
            JarSigner signer = new JarSigner.Builder(pk,
                    CertificateFactory.getInstance("X.509").generateCertPath(
                            Collections.singletonList(cert)))
                    .build();
        // Sign jar
        try (ZipFile src = new JarFile(jarName);
                FileOutputStream out = new FileOutputStream(SIGNED_JAR)) {
            signer.sign(src,out);
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:MVJarSigningTest.java

示例2: initFingerprintManager

import java.security.KeyStore; //导入方法依赖的package包/类
private void initFingerprintManager() throws Throwable {
    mFpManager = (FingerprintManager) mContext.getSystemService(Context.FINGERPRINT_SERVICE);
    if (!mFpManager.isHardwareDetected())
        throw new IllegalStateException("Fingerprint hardware not present");

    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    KeyGenerator keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    keyStore.load(null);
    keyGenerator.init(new KeyGenParameterSpec.Builder(
            KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .build());
    keyGenerator.generateKey();

    Cipher cipher = Cipher.getInstance(
            KeyProperties.KEY_ALGORITHM_AES + "/" +
            KeyProperties.BLOCK_MODE_CBC + "/" +
            KeyProperties.ENCRYPTION_PADDING_PKCS7);
    SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
    cipher.init(Cipher.ENCRYPT_MODE, key);

    mFpHandler = new FingerprintHandler(cipher);

    if (DEBUG) log("Fingeprint manager initialized");
}
 
开发者ID:WrBug,项目名称:GravityBox,代码行数:28,代码来源:FingerprintLauncher.java

示例3: getKeyStoreKey

import java.security.KeyStore; //导入方法依赖的package包/类
private static Key getKeyStoreKey(KeyStore ks, String keyAlias, List<char[]> passwords)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    UnrecoverableKeyException lastFailure = null;
    for (char[] password : passwords) {
        try {
            return ks.getKey(keyAlias, password);
        } catch (UnrecoverableKeyException e) {
            lastFailure = e;
        }
    }
    if (lastFailure == null) {
        throw new RuntimeException("No key passwords");
    } else {
        throw lastFailure;
    }
}
 
开发者ID:F8LEFT,项目名称:FApkSigner,代码行数:17,代码来源:ApkSignerTool.java

示例4: loadCertificate

import java.security.KeyStore; //导入方法依赖的package包/类
public static CertificateInfo loadCertificate(KeystoreConfiguration configuration)
    throws GeneralSecurityException, IOException {
  try {
    KeyStore keyStore = KeyStore.getInstance(configuration.getType());
    keyStore.load(getResourceAsStream(configuration.getLocation()), configuration.getPassword().toCharArray());

    Key key = keyStore.getKey(configuration.getAlias(), configuration.getKeyPassword().toCharArray());
    if (key instanceof PrivateKey) {
      X509Certificate certificate = (X509Certificate) keyStore.getCertificate(configuration.getAlias());
      PublicKey publicKey = certificate.getPublicKey();
      KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);
      return new CertificateInfo(certificate, keyPair);
    } else {
      throw new GeneralSecurityException(configuration.getAlias() + " is not a private key!");
    }
  } catch (IOException | GeneralSecurityException e) {
    log.error("Keystore configuration: [{}] is invalid!", configuration, e);
    throw e;
  }
}
 
开发者ID:osswangxining,项目名称:iotgateway,代码行数:21,代码来源:ConfigurationTools.java

示例5: runTest

import java.security.KeyStore; //导入方法依赖的package包/类
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:18,代码来源:MetadataEmptyTest.java

示例6: buildSignedMultiReleaseJar

import java.security.KeyStore; //导入方法依赖的package包/类
public void buildSignedMultiReleaseJar() throws Exception {
    String testsrc = System.getProperty("test.src",".");
    String testdir = findTestDir(testsrc);
    String keystore = testdir + "/sun/security/tools/jarsigner/JarSigning.keystore";

    // jarsigner -keystore keystore -storepass "bbbbbb"
    //           -signedJar signed-multi-release.jar multi-release.jar b

    char[] password = "bbbbbb".toCharArray();
    KeyStore ks = KeyStore.getInstance(new File(keystore), password);
    PrivateKey pkb = (PrivateKey)ks.getKey("b", password);
    CertPath cp = CertificateFactory.getInstance("X.509")
            .generateCertPath(Arrays.asList(ks.getCertificateChain("b")));
    JarSigner js = new JarSigner.Builder(pkb, cp).build();
    try (ZipFile in = new ZipFile("multi-release.jar");
         FileOutputStream os = new FileOutputStream("signed-multi-release.jar"))
    {
        js.sign(in, os);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:CreateMultiReleaseTestJars.java

示例7: loadPublicKeyFromKeyStore

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * 从KeyStore获取公钥
 * @param location
 * @param alias
 * @param storeType
 * @param storePass
 * @param keyPass
 * @return
 */
public static PublicKey loadPublicKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
    try {
        storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        keyPass = keyPass == null ? storePass : keyPass;
        KeyStore keyStore = KeyStore.getInstance(storeType);
        InputStream is = new FileInputStream(location);
        keyStore.load(is, storePass.toCharArray());

        RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
        RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
                key.getPublicExponent());
        PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
        return publicKey;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:warlock-china,项目名称:azeroth,代码行数:27,代码来源:RSA.java

示例8: validateKeyPassword

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 *
 * @param keystorePath
 * @param keyName
 * @param encodedPassword
 * @throws UnrecoverableKeyException if the password is invalid
 */
public static void validateKeyPassword( String keystorePath, String keyName, String encodedPassword)
    throws Exception
{
    char[] password = null;
    try {
        KeyStore ks = KeyStoreFileManager.loadKeyStore( keystorePath, (char[])null);
        password = PasswordObfuscator.getInstance().decodeAliasPassword(keystorePath,keyName, encodedPassword);
        ks.getKey(keyName, password);
    } finally {
        if (password != null) PasswordObfuscator.flush(password);
    }

}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:21,代码来源:KeyStoreFileManager.java

示例9: getCredentials

import java.security.KeyStore; //导入方法依赖的package包/类
@Override
public Properties getCredentials(final Properties securityProperties,
    final DistributedMember server, final boolean isPeer) throws AuthenticationFailedException {
  final String keyStorePath = securityProperties.getProperty(KEYSTORE_FILE_PATH);
  if (keyStorePath == null) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: key-store file path property [" + KEYSTORE_FILE_PATH + "] not set.");
  }

  final String alias = securityProperties.getProperty(KEYSTORE_ALIAS);
  if (alias == null) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: key alias name property [" + KEYSTORE_ALIAS + "] not set.");
  }

  final String keyStorePass = securityProperties.getProperty(KEYSTORE_PASSWORD);

  try {
    final KeyStore ks = KeyStore.getInstance("PKCS12");
    final char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
    final FileInputStream certificatefile = new FileInputStream(keyStorePath);

    try {
      ks.load(certificatefile, passPhrase);
    } finally {
      certificatefile.close();
    }

    final Key key = ks.getKey(alias, passPhrase);

    if (key instanceof PrivateKey) {
      final PrivateKey privKey = (PrivateKey) key;
      final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
      final Signature sig = Signature.getInstance(cert.getSigAlgName());

      sig.initSign(privKey);
      sig.update(alias.getBytes("UTF-8"));
      final byte[] signatureBytes = sig.sign();

      final Properties newprops = new Properties();
      newprops.put(KEYSTORE_ALIAS, alias);
      newprops.put(SIGNATURE_DATA, signatureBytes);
      return newprops;

    } else {
      throw new AuthenticationFailedException(
          "PKCSAuthInit: " + "Failed to load private key from the given file: " + keyStorePath);
    }

  } catch (Exception ex) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: Exception while getting credentials: " + ex, ex);
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:55,代码来源:PKCSAuthInit.java

示例10: SoftTokenMacContentSignerBuilder

import java.security.KeyStore; //导入方法依赖的package包/类
public SoftTokenMacContentSignerBuilder(String keystoreType, InputStream keystoreStream,
        char[] keystorePassword, String keyname, char[] keyPassword)
        throws XiSecurityException {
    if (!"JCEKS".equalsIgnoreCase(keystoreType)) {
        throw new IllegalArgumentException("unsupported keystore type: " + keystoreType);
    }
    ParamUtil.requireNonNull("keystoreStream", keystoreStream);
    ParamUtil.requireNonNull("keystorePassword", keystorePassword);
    ParamUtil.requireNonNull("keyPassword", keyPassword);

    try {
        KeyStore ks = KeyUtil.getKeyStore(keystoreType);
        ks.load(keystoreStream, keystorePassword);

        String tmpKeyname = keyname;
        if (tmpKeyname == null) {
            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    tmpKeyname = alias;
                    break;
                }
            }
        } else {
            if (!ks.isKeyEntry(tmpKeyname)) {
                throw new XiSecurityException("unknown key named " + tmpKeyname);
            }
        }

        this.key = (SecretKey) ks.getKey(tmpKeyname, keyPassword);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException
            | CertificateException | IOException | UnrecoverableKeyException
            | ClassCastException ex) {
        throw new XiSecurityException(ex.getMessage(), ex);
    }
}
 
开发者ID:xipki,项目名称:xitk,代码行数:38,代码来源:SoftTokenMacContentSignerBuilder.java

示例11: getPrivateKey

import java.security.KeyStore; //导入方法依赖的package包/类
@Override
public PrivateKey getPrivateKey(String alias) {
    Log.i(TAG, "getPrivateKey for " + alias);
    try {
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        return (PrivateKey) ks.getKey(alias, null);
    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | UnrecoverableKeyException e) {
        Log.e(TAG, "Error during getPrivateKey(" + alias + ")", e);
    }
    return null;
}
 
开发者ID:RomascuAndrei,项目名称:BTNotifierAndroid,代码行数:13,代码来源:SslUtils.java

示例12: signZip

import java.security.KeyStore; //导入方法依赖的package包/类
public void signZip(URL keystoreURL,
                    String keystoreType,
                    char[] keystorePw,
                    String certAlias,
                    char[] certPw,
                    String signatureAlgorithm,
                    String inputZipFilename,
                    String outputZipFilename)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        IOException, GeneralSecurityException {
    InputStream keystoreStream = null;


    try {
        KeyStore keystore = null;
        if (keystoreType == null) keystoreType = KeyStore.getDefaultType();
        keystore = KeyStore.getInstance(keystoreType);

        keystoreStream = keystoreURL.openStream();
        keystore.load(keystoreStream, keystorePw);
        Certificate cert = keystore.getCertificate(certAlias);
        X509Certificate publicKey = (X509Certificate) cert;
        Key key = keystore.getKey(certAlias, certPw);
        PrivateKey privateKey = (PrivateKey) key;

        setKeys("custom", publicKey, privateKey, signatureAlgorithm, null);

        signZip(inputZipFilename, outputZipFilename);
    } finally {
        if (keystoreStream != null) keystoreStream.close();
    }
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:33,代码来源:ZipSigner.java

示例13: execute0

import java.security.KeyStore; //导入方法依赖的package包/类
@Override
protected Object execute0() throws Exception {
    KeyStore ks = KeyStore.getInstance("PKCS11", XiSecurityConstants.PROVIDER_NAME_XIPKI);
    ks.load(null, null);
    if (verbose.booleanValue()) {
        println("available aliases:");
        Enumeration<?> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias2 = (String) aliases.nextElement();
            println("    " + alias2);
        }
    }

    String alias = getAlias();
    println("alias: " + alias);
    PrivateKey key = (PrivateKey) ks.getKey(alias, null);
    if (key == null) {
        println("could not find key with alias '" + alias + "'");
        return null;
    }

    Certificate cert = ks.getCertificate(alias);
    if (cert == null) {
        println("could not find certificate to verify signature");
        return null;
    }
    PublicKey pubKey = cert.getPublicKey();

    String sigAlgo = "SM3withSM2";
    println("signature algorithm: " + sigAlgo);
    Signature sig = Signature.getInstance(sigAlgo, XiSecurityConstants.PROVIDER_NAME_XIPKI);

    if (StringUtil.isNotBlank(ida)) {
        sig.setParameter(new XiSM2ParameterSpec(ida.getBytes()));
    }

    sig.initSign(key);

    byte[] data = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    sig.update(data);
    byte[] signature = sig.sign(); // CHECKSTYLE:SKIP
    println("signature created successfully");

    Signature ver = Signature.getInstance(sigAlgo, "BC");
    if (StringUtil.isNotBlank(ida)) {
        ver.setParameter(new SM2ParameterSpec(ida.getBytes()));
    }

    ver.initVerify(pubKey);
    ver.update(data);
    boolean valid = ver.verify(signature);
    println("signature valid: " + valid);
    return null;
}
 
开发者ID:xipki,项目名称:xitk,代码行数:55,代码来源:P11ProviderSm2TestCmd.java

示例14: encryptData

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Encrypt given bytes and persist contents to File with given filename.
 * @param input - byte[] to encrypt
 * @param fileName - String name of the encrypted file
 * @return String representing encrypted file or null if encryption fails.
 * @throws Exception - Throws Exceptions related to encryption
 */
private String encryptData(final byte [] input,  final String fileName) throws Exception{

  String encryptedDataFilePath;

  final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
  keyStore.load(null);

  // Does the key need to be created?
  if (!keyStore.containsAlias(ALIAS)){
    createNewKey();
  }
  final SecretKey key = (SecretKey) keyStore.getKey(ALIAS, null);

  final Cipher c = Cipher.getInstance(CIPHER_TYPE);
  c.init(Cipher.ENCRYPT_MODE, key);

  // Persist the GCMParamterSpec bytes to file for later use
  GCMParameterSpec spec = c.getParameters().getParameterSpec(GCMParameterSpec.class);
   final FileOutputStream fos = new FileOutputStream(getFilePath(Constants.IV_FILE));
  fos.write(spec.getIV());
  Log.i(TAG, "IV Length is " + spec.getIV().length+ " tag length is " + spec.getTLen());
  fos.close();

  encryptedDataFilePath = getFilePath(fileName);

  final CipherOutputStream cipherOutputStream =
      new CipherOutputStream(
          new FileOutputStream(encryptedDataFilePath), c);
  cipherOutputStream.write(input);
  cipherOutputStream.close();

  return encryptedDataFilePath;
}
 
开发者ID:Esri,项目名称:mapbook-android,代码行数:41,代码来源:CredentialCryptographer.java

示例15: 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());
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:57,代码来源:WriteP12Test.java


注:本文中的java.security.KeyStore.getKey方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。