Reputation: 51
Hi I have the following function to convert a string into a PrivateKey in my application:
public static PrivateKey main() throws Exception {
// Read in the key into a String
StringBuilder pkcs8Lines = new StringBuilder();
BufferedReader rdr = new BufferedReader(new StringReader(PRIVATE_KEY));
String line;
while ((line = rdr.readLine()) != null) {
pkcs8Lines.append(line);
}
// Remove the "BEGIN" and "END" lines, as well as any whitespace
String pkcs8Pem = pkcs8Lines.toString();
pkcs8Pem = pkcs8Pem.replaceAll("\\n+","");
// Base64 decode the result
byte [] pkcs8EncodedBytes = Base64.decode(pkcs8Pem, Base64.DEFAULT);
// extract the private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("SHA1WITHRSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
return privKey;
}
and I get the following exception:
W/System.err: java.security.NoSuchAlgorithmException: SHA1withRSA KeyFactory not available W/System.err: at java.security.KeyFactory.(KeyFactory.java:161) at java.security.KeyFactory.getInstance(KeyFactory.java:195)
so I have tried to find all the alghoritms I can use through this code:
TreeSet<String> algorithms = new TreeSet<>();
for (Provider provider : Security.getProviders())
for (Provider.Service service : provider.getServices())
if (service.getType().equals("Signature"))
algorithms.add(service.getAlgorithm());
for (String algorithm : algorithms)
System.out.println(algorithm);
and in the response "SHA1withRSA" is included, do you know where the problem is?
Upvotes: 1
Views: 1007
Reputation: 845
SHA1withRSA is a signature type, you see that in the list because you have
if (service.getType().equals("Signature"))
If you edit that to
if (service.getType().equals("KeyFactory"))
you should see a list that looks something like this
DSA
EC
RSA
RSASSA-PSS
X25519
X448
XDH
Upvotes: 2