我正在使用Java(jdk 1.7)和bouncycastle库来获取p7m签名文件的内容。
在构建路径中,添加了以下文件:
bcpkix-jdk15on-160.jar
commons-io-2.1.jar
log4j-1.2.17.jar
bcprov-ext-jdk15on-160.jar
bcprov-jdk15on-160.jar
这是我正在使用的代码:
public static void main(String[] args) throws Exception {
File f = new File("E:\\test\\file.xml.p7m");
logger.debug(f.getAbsolutePath());
byte[] content = org.apache.commons.io.FileUtils.readFileToByteArray(f);
byte[] contentUnsigned = removeP7MCodes(f.getName(), content);
if (contentUnsigned != null)
logger.debug(new String(contentUnsigned));
}
public static byte[] removeP7MCodes(final String fileName, final byte[] p7bytes) {
try {
if (p7bytes == null)
return p7bytes;
if (!fileName.toUpperCase().endsWith(".P7M")) {
return p7bytes;
}
// This is where I get the exception
CMSSignedData cms = new CMSSignedData(p7bytes);
if (cms.getSignedContent() == null) {
logger.error("Unable to find signed Content during decoding from P7M for file: " + fileName);
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
cms.getSignedContent().write(out);
return out.toByteArray();
} catch (CMSException e) {
logger.error("CMSException from P7M for file: " + fileName, e);
} catch (IOException e) {
logger.error("IOException from P7M for file: " + fileName, e);
}
return null;
}
对于我测试过的大多数p7m,它都可以正常工作,没有错误/问题。
有些p7m文件无法解码,并且出现以下错误(我尝试使用在线工具进行验证,并且这些文件是真实的):
11:01:30 DEBUG [DecoderTester:45] - E:\test\file.xml.p7m
11:01:30 ERROR [DecoderTester:75] - CMSException from P7M for file: file.xml.p7m
org.bouncycastle.cms.CMSException: Malformed content.
at org.bouncycastle.cms.CMSUtils.readContentInfo(Unknown Source)
at org.bouncycastle.cms.CMSUtils.readContentInfo(Unknown Source)
at org.bouncycastle.cms.CMSSignedData.<init>(Unknown Source)
at com.decoder.DecoderTester.removeP7MCodes(DecoderTester.java:63)
at com.decoder.DecoderTester.main(DecoderTester.java:48)
Caused by: java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.asn1.DERApplicationSpecific
at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source)
at org.bouncycastle.asn1.cms.ContentInfo.getInstance(Unknown Source)
... 5 more
我尝试删除以下两个库之间的一个库:bcprov-ext-jdk15on-160.jar
和bcprov-jdk15on-160.jar
,但出现相同的错误。
您有什么想法吗?