我的應用程序使用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