/** java.security.KeyStore#getKey(java.lang.String, char[]) */ public void test_getKeyLjava_lang_String$C() throws Exception { // Test for method java.security.Key // java.security.KeyStore.getKey(java.lang.String, char[]) // creatCertificate(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert[] = new X509Certificate[2]; cert[0] = (X509Certificate) cf.generateCertificate(certArray); cert[1] = (X509Certificate) cf.generateCertificate(certArray2); KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType()); keyTest.load(null, null); keyTest.setKeyEntry("alias2", getPrivateKey(), pssWord, cert); PrivateKey returnedKey = (PrivateKey) keyTest.getKey("alias2", pssWord); byte[] retB = returnedKey.getEncoded(); byte[] priB = getPrivateKey().getEncoded(); assertTrue(Arrays.equals(retB, priB)); assertEquals(getPrivateKey().getAlgorithm(), returnedKey.getAlgorithm()); assertEquals(getPrivateKey().getFormat(), returnedKey.getFormat()); try { keyTest.getKey("alias2", "wrong".toCharArray()); fail(); } catch (UnrecoverableKeyException expected) { } keyTest.setCertificateEntry("alias1", cert[1]); assertNull( "the private key returned from getKey for a certificate entry is not null", keyTest.getKey("alias1", pssWord)); }
public PrivateKey getPrivateKey(String alias) { PrivateKey pk = keyManager.getPrivateKey(alias); if (Debug.verboseOn()) Debug.logVerbose( "getPrivateKey for alias [" + alias + "] got " + (pk == null ? "[Not Found!]" : "[alg:" + pk.getAlgorithm() + ";format:" + pk.getFormat() + "]"), module); // Debug.logInfo(new Exception(), "Location where getPrivateKey is called", module); return pk; }
// internal implementation of translateKey() for private keys. See JCA doc private PrivateKey translatePrivateKey(PrivateKey key) throws InvalidKeyException { if (key instanceof RSAPrivateCrtKey) { if (key instanceof RSAPrivateCrtKeyImpl) { return key; } RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; try { return new RSAPrivateCrtKeyImpl( rsaKey.getModulus(), rsaKey.getPublicExponent(), rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), rsaKey.getPrimeQ(), rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), rsaKey.getCrtCoefficient()); } catch (RuntimeException e) { // catch providers that incorrectly implement RSAPrivateCrtKey throw new InvalidKeyException("Invalid key", e); } } else if (key instanceof RSAPrivateKey) { if (key instanceof RSAPrivateKeyImpl) { return key; } RSAPrivateKey rsaKey = (RSAPrivateKey) key; try { return new RSAPrivateKeyImpl(rsaKey.getModulus(), rsaKey.getPrivateExponent()); } catch (RuntimeException e) { // catch providers that incorrectly implement RSAPrivateKey throw new InvalidKeyException("Invalid key", e); } } else if ("PKCS#8".equals(key.getFormat())) { byte[] encoded = key.getEncoded(); return RSAPrivateCrtKeyImpl.newKey(encoded); } else { throw new InvalidKeyException( "Private keys must be instance " + "of RSAPrivate(Crt)Key or have PKCS#8 encoding"); } }