【问题标题】:Android - InvalidKeySpecException - java lang runtime exception SSLInternal:TOO_LONG when trying to read .der fileAndroid - InvalidKeySpecException - java lang 运行时异常 SSLInternal:TOO_LONG 尝试读取 .der 文件时
【发布时间】:2018-05-01 07:04:57
【问题描述】:

我正在尝试从 der 文件中读取 私钥。我在我的 logcat 中收到以下错误。并且返回值为空。

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000af:ASN.1 编码例程:OPENSSL_internal:TOO_LONG

我尝试搜索已经发生过这种情况但没有找到的情况。我想知道这个错误是什么意思以及如何解决它。

这是我的代码:

public static String decryptionWithFile(String encrypted,String privateFile2)throws Exception  {
    PrivateKey privateKey = getPrivateKey(privateFile2);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] bts = Hex.decodeHex(encrypted.toCharArray());
    bts = cipher.doFinal(bts);


    bts = getFinalBytesOfDycryptedString(bts);
    String decryptedMessage = new String(cipher.doFinal(encrypted.getBytes()));
    return new String(bts,"UTF-8");
}

这里是 getPrivateKey();方法:

private static PrivateKey getPrivateKey(String privateFile2)throws Exception  {
    File f = new File(privateFile2);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
    return privKey;
}

重要提示:我将 .der 文件添加到我的资产文件夹中,然后将其保存到内部存储中的一个文件中,以便访问我的功能所需的路径。您认为在此过程中文件一定发生了什么事吗? (使用公钥可以正常工作)

【问题讨论】:

  • 您是否从文件中正确获取了私钥。你有没有通过打印日志检查过??

标签: java android encryption private-key der


【解决方案1】:

问题出在我的猜测上。当我将 .der 文件写入内部存储时,它以某种方式被更改,因此无法正常工作。

所以取而代之。我直接使用 getAssets().open(filename) 返回的InputStream 来读取私钥。这样就解决了。

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多