java-使用包含PEM公钥的PEM编码的X.509证书加密令牌文件,并生成.p7m格式的内容

时间:2018-06-24 20:32:28

标签: java encryption

我正在尝试编写一个Java应用程序来模拟Apple DEP服务器。它需要包含PEM公钥的PEM编码的X.509证书,并以.p7m格式返回令牌。我有一个PEM编码的X.509证书,但是当我尝试使用下面的代码片段加密令牌文件时,出现错误“ javax.crypto.IllegalBlockSizeException:数据不得超过245个字节”。

这是我的代码段。

    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("token1.txt");
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String content = s.hasNext() ? s.next() : "";

    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    File f = new File("cert.pem");
    FileInputStream fis = new FileInputStream (f);
    X509Certificate cer = (X509Certificate) fact.generateCertificate(fis);
    PublicKey key = cer.getPublicKey();

    String token = encrypt(content, key);

例外:

Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at com.vmware.depmock.controllers.TokenTest.encrypt(TokenTest.java:41)
at com.vmware.depmock.controllers.TokenTest.main(TokenTest.java:68)

因此,我尝试将令牌文件的内容限制为245个字符以下。我能够加密令牌文件,但是客户端不接受该文件(用.net编写),并且返回了错误

'System.InvalidCastException: Unable to cast object of type 'Org.BouncyCastle.Asn1.DerInteger' to type 'Org.BouncyCastle.Asn1.Asn1SequenceParser'.   at Org.BouncyCastle.Cms.CmsContentInfoParser..ctor(Stream data)'

0 个答案:

没有答案