【问题标题】:(Android / Java) Create a RSA private key instance(Android/Java) 创建 RSA 私钥实例
【发布时间】:2017-02-13 11:28:28
【问题描述】:

我正在尝试从 pem 文件在 Android 应用程序中创建 PrivateKey 实例以解密某些数据,但出现以下错误:

java.lang.RuntimeException: 错误:0c0890ba:ASN.1 编码例程:asn1_check_tlen:WRONG_TAG

代码:

// Read private key.
InputStream is = context.getResources().openRawResource(R.raw.private_key);
br = new BufferedReader(new InputStreamReader(is));
List<String> lines = new ArrayList<String>();
line = null;
while ((line = br.readLine()) != null)
    lines.add(line);

// Removes the first and last lines of the file (comments).
if (lines.size() > 1 && lines.get(0).startsWith("-----") &&
        lines.get(lines.size()-1).startsWith("-----")) {
    lines.remove(0);
    lines.remove(lines.size()-1);
}

// Concats the remaining lines to a single String.
StringBuilder sb = new StringBuilder();
for (String aLine: lines)
    sb.append(aLine);
String keyString = sb.toString();

// Converts the String to a PublicKey instance
byte[] keyBytes = Base64.decode(keyString, Base64.DEFAULT);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
mKey = keyFactory.generatePrivate(spec);

有什么帮助吗?

【问题讨论】:

  • 您的密钥是 PKCS#8 格式还是 PKCS#1 格式?它以----BEGIN PRIVATE KEY---------BEGIN RSA PRIVATE KEY----- 开头?在第二种情况下,您需要将其转换为 pcks8
  • 你是对的 pedrofb,如果你想让我将它设置为正确答案,请将你的评论作为答案。

标签: java android encryption rsa private-key


【解决方案1】:

看来您的密钥不是 PKCS8 格式。 Java 不支持以 PKCS#1 格式加载密钥。检查您的密钥是否为 PKCS#8 格式,验证它是否以 -----BEGIN PRIVATE KEY----- 开头如果它以 ----BEGIN RSA PRIVATE KEY----- 开头,那么您需要将其转换为 PKCS#8。见Convert PEM traditional private key to PKCS8 private key

【讨论】:

    【解决方案2】:

    使用这行代码:

        if (privateKeyString.contains("-----BEGIN PRIVATE KEY-----") || privateKeyString.contains("-----END PRIVATE KEY-----"))
            privateKeyString = privateKeyString.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");
    
    
        if (privateKeyString.contains("-----BEGIN RSA PRIVATE KEY-----") || privateKeyString.contains("-----END RSA PRIVATE KEY-----"))
            privateKeyString = privateKeyString.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", "");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-18
      • 2013-12-04
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多