我在找一些C#代码转换为Java中的等价物。

在C#代码需要一些串的内容,和签名(用专用密钥产生,一个单独的机器上),并用它来验证签名相匹配的公共密钥相结合,提供保证的电平,该请求还没有被篡改用。

  public bool VerifySignature(string content, byte[] signatureBytes, AsymmetricAlgorithm publicKey)
  {
        var hash = new MD5CryptoServiceProvider();

        byte[] dataBuffer = Encoding.ASCII.GetBytes(content);

        var cs = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write);
        cs.Write(dataBuffer, 0, dataBuffer.Length);
        cs.Close();

        var deformatter = new RSAPKCS1SignatureDeformatter(publicKey);
        deformatter.SetHashAlgorithm("MD5");

        return deformatter.VerifySignature(hash, signatureBytes);
  }

公钥本身是一个X509证书 - 从.cer文件构成,存储作为组件资源即

byte[] data; // data is read from a resource stream.
var publicKey = new X509Certificate2(data, "", X509KeyStorageFlags.MachineKeySet).PublicKey.Key

什么我希望做的是模拟在Java中此功能,这样我就可以通过验证C#中的一些代码生成的签名......我已经开始调查了Java的加密功能,但我一点一个java菜鸟。下面是我想出迄今:

byte[] certContents=null;
byte[] signature=null;
String contents = "abc";

// load cert
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certContents));

// grab public key
RSAPublicKey publicKey = (RSAPublicKey)cert.getPublicKey();

// get sha1 hash for contents        
Mac mac = Mac.getInstance("HmacSHA1");
mac.update(contents.getBytes());                
byte[] hash = mac.doFinal();

// get cipher
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);

// verify signature of contents matches signature passed to method somehow (and this is where I'm stuck)

谁能提供任何洞察我如何验证签名 - 或者提供链接到一些资源,这或许可以解释的java.crypto和java.security.cert中使用的更好,然后磨Java文档的运行

有帮助吗?

解决方案

这是C#代码看起来让人有些困惑了我。它使用SHA1CryptoServiceProvider但使用MD5哈希,所以我不能告诉它使用的哈希算法。我假定它是MD5。

在签名验证过程涉及填充使您的代码将无法正常工作。以下是从我的代码一些片断,你可以用它来验证签名。数据是字节签署和sigBytes持有的签名。

String algorithm = "MD5withRSA";

// Initialize JCE provider    
Signature verifier = Signature.getInstance(algorithm);

// Do the verification   
boolean result=false;

try {
    verifier.initVerify(cert); // This one checks key usage in the cert
    verifier.update(data);
    result = verifier.verify(sigBytes);
}
catch (Exception e) {
    throw new VerificationException("Verification error: "+e, e);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top