繁体   English   中英

SHA1withRSA NoSuchAlgorithmException

[英]SHA1withRSA NoSuchAlgorithmException

您好我有以下 function 在我的应用程序中将字符串转换为 PrivateKey:

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;
}

我得到以下异常:

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 )

所以我试图通过这段代码找到我可以使用的所有算法:

        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);

并且在响应中包含“SHA1withRSA”,您知道问题出在哪里吗?

SHA1withRSA 是一种签名类型,您可以在列表中看到它,因为您有

if (service.getType().equals("Signature"))

如果您将其编辑为

if (service.getType().equals("KeyFactory"))

你应该看到一个看起来像这样的列表

DSA
EC
RSA
RSASSA-PSS
X25519
X448
XDH

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM