开发者社区> 问答> 正文

加载RSA公钥错误DerInputStream.getLength():lengthTag = 10

我需要加密JSON数据,以便使用公共RSA密钥在http正文中发送它,我加载了公共RSA密钥文件(.der),并且工作正常。

客户端向我发送了一个公共RSA密钥文件(.bin)。因此,当我运行程序时,出现此错误

Caused by: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=109, too big.
    at sun.security.x509.X509Key.decode(X509Key.java:380) ~[na:1.6.0_45]
    at sun.security.x509.X509Key.decode(X509Key.java:386) ~[na:1.6.0_45]
    at sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:66) ~[na:1.6.0_45

我的PublicKeyReader类:

public class PublicKeyReader {

  public static PublicKey getpublicKey(String filename)
    throws Exception {

      File file = new File(filename);
      FileInputStream fis = new FileInputStream(filename);
      DataInputStream dis = new DataInputStream(fis);
      byte[] keyBytes = new byte[(int) file.length()];
      dis.readFully(keyBytes);
      dis.close();


    X509EncodedKeySpec spec =
      new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");

    return kf.generatePublic(spec);
  }
}

在我的主类中,加密部分是:

// Encrypt Data with AES
        byte[] keyData = random.generateSeed(16);
        SecretKey skeySpec = new SecretKeySpec(keyData, "AES");
        Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] ivParams = new byte[aes.getBlockSize()];
        IvParameterSpec iv = new IvParameterSpec(ivParams);
        aes.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        // Lecture du certificat (cle publique RSA)
        PublicKey clePublique = PublicKeyReader.getpublicKey("./src/main/resources/publique.bin");
        //String clePublique1 = Base64.encodeBase64String(clePublique.getEncoded()).replaceAll(
        //      "(\\r|\\n)", "");
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.WRAP_MODE, clePublique);
        byte[] wrappedKey = cipher.wrap(skeySpec);

        // encodedToken : Mot de passe symétrique crypté avec le certificat
        // public (RSA) mis à la disposition de la banque par BAM
        String encodedToken = Base64.encodeBase64String(wrappedKey).replaceAll(
                "(\\r|\\n)", "");
        ;

展开
收起
垚tutu 2019-12-04 16:25:24 3386 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多