8205720: KeyFactory#getKeySpec and translateKey thorws NullPointerException with Invalid key

Updated SunRsaSign provider to check and throw InvalidKeyException for null key algo/format/encoding

Reviewed-by: xuelei
This commit is contained in:
Valerie Peng 2018-06-30 00:33:05 +00:00
parent 11184615a8
commit ecc5979769
4 changed files with 33 additions and 21 deletions

View file

@ -100,7 +100,7 @@ public class RSAKeyFactory extends KeyFactorySpi {
private static void checkKeyAlgo(Key key, String expectedAlg)
throws InvalidKeyException {
String keyAlg = key.getAlgorithm();
if (!(keyAlg.equalsIgnoreCase(expectedAlg))) {
if (keyAlg == null || !(keyAlg.equalsIgnoreCase(expectedAlg))) {
throw new InvalidKeyException("Expected a " + expectedAlg
+ " key, but got " + keyAlg);
}
@ -123,8 +123,7 @@ public class RSAKeyFactory extends KeyFactorySpi {
return (RSAKey)key;
} else {
try {
String keyAlgo = key.getAlgorithm();
KeyType type = KeyType.lookup(keyAlgo);
KeyType type = KeyType.lookup(key.getAlgorithm());
RSAKeyFactory kf = RSAKeyFactory.getInstance(type);
return (RSAKey) kf.engineTranslateKey(key);
} catch (ProviderException e) {
@ -268,8 +267,7 @@ public class RSAKeyFactory extends KeyFactorySpi {
throw new InvalidKeyException("Invalid key", e);
}
} else if ("X.509".equals(key.getFormat())) {
byte[] encoded = key.getEncoded();
RSAPublicKey translated = new RSAPublicKeyImpl(encoded);
RSAPublicKey translated = new RSAPublicKeyImpl(key.getEncoded());
// ensure the key algorithm matches the current KeyFactory instance
checkKeyAlgo(translated, type.keyAlgo());
return translated;
@ -313,8 +311,8 @@ public class RSAKeyFactory extends KeyFactorySpi {
throw new InvalidKeyException("Invalid key", e);
}
} else if ("PKCS#8".equals(key.getFormat())) {
byte[] encoded = key.getEncoded();
RSAPrivateKey translated = RSAPrivateCrtKeyImpl.newKey(encoded);
RSAPrivateKey translated =
RSAPrivateCrtKeyImpl.newKey(key.getEncoded());
// ensure the key algorithm matches the current KeyFactory instance
checkKeyAlgo(translated, type.keyAlgo());
return translated;