java - SHA1withRSA NoSuchAlgorithmException

标签 java android rsa sha1

您好,我有以下函数可以在我的应用程序中将字符串转换为私钥:

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

关于java - SHA1withRSA NoSuchAlgorithmException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58923401/

相关文章:

java - 使用有界通配符推断类型的问题

java - 在 Java 中从 Double 转换为 String 的十进制错误

android - Android 4 的人脸检测 API 是否依赖于特定手机?

git - 从 Cpanel git 克隆项目,显示此错误 "ssh remote host identification has changed"

java - Bouncy CasSTLe J2ME加载现有私钥

java - 如何修复线性方程面向对象程序中的错误?

java - 使用文件编号计算 GCM - NoSuchElementException

java - 将样式应用于 Android 字符串中的文本

linux - 如何使用 openssl 识别证书的 RSA 签名中使用的填充方案?

java - 创建名称为 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration' 的 bean 时出错 :