我的应用程序使用java安全API签名文件并进行验证。 签名时,我使用PFX文件和密码作为输入,签名后我使用字节生成签名文件。 验证过程中,我使用签名文件,证书文件和签名文件作为输入。 请找我正在使用的验证代码如下:我的代码可以验证自签名证书,但在使用威瑞信颁发证书时失败
// KeyFilePath= path of certificate file
// fileToVerify = path of signed file
// signatureFilePath = path of signature file
InputStream inputStream = new FileInputStream(KeyFilePath);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
// input the signature bytes
String sigFile = signatureFilePath;
FileInputStream sigFileInputStream = new FileInputStream(sigFile);
byte[] sigToVerify = new byte[sigFileInputStream.available()];
sigFileInputStream.read(sigToVerify);
sigFileInputStream.close();
PublicKey pubKey = x509Certificate.getPublicKey();
Signature signature = Signature.getInstance(signAlgorithm);
signature.initVerify(pubKey);
// Update and verify the data
try {
FileInputStream dataFileInputStream = new FileInputStream(fileToVerify);
BufferedInputStream bufferedInputStream = new BufferedInputStream(dataFileInputStream);
byte[] buffer = new byte[IVerifyDigitalSignature.BYTE_SIZE];
int bufferedInputStreamLength;
while (bufferedInputStream.available() != IVerifyDigitalSignature.ZERO_LENGTH) {
bufferedInputStreamLength = bufferedInputStream.read(buffer);
signature.update(buffer, IVerifyDigitalSignature.ZERO_LENGTH, bufferedInputStreamLength);
}
bufferedInputStream.close();
// Verify the Signature
x509Certificate.verify(pubKey);
verifyDigitalSignature = signature.verify(sigToVerify);
请帮我解决同样的,因为它尚未关闭。
'byte [] sigToVerify = new byte [sigFileInputStream.available()];'记录为'InputStream.available()'的不正确使用,所以将它与0比较以作为流结束的测试。 – EJP 2014-11-05 09:24:15
自签名证书是由其“自己的”密钥签署的,或者更确切地说是由其公共一半在证书中的私钥的一半签名的。因此'x509certificate.verify(pubkey)'成功了,但基本上没用,因为任何攻击者都可以自签署欺诈证书。 CA签名的证书由CA(私人)密钥签名,因此,通过查找* parent *(CA)证书并使用*那个pubkey,子证书可以并且通常必须被验证,迭代直到您到达根CA是自签名的,并且只能因为它是手动信任的(通常位于信任库文件中)而可以信任。 ... – 2014-11-05 12:27:01
...除了有效的签名外,还有其他一些需要验证的证书链是有效的(不伪造或被破坏的)。这通常称为PKI验证,或者更具体地说PKIX验证,因为该格式(X.509证书等)为因特网分析)是最常见的。对于Java,http://docs.oracle.com/javase/7/docs/technotes/guides/security/certpath/CertPathProgGuide.html是一个相当不错的开始。 – 2014-11-05 12:29:45