需要实现一个和java一样功能的C#函数,
java原代码如下(参考连接:http://ajava.org/course/safe/12328.html):
public static String sign(byte[] data, String privateKey) throws Exception {
// 解密由base64编码的私钥
byte[] keyBytes = decryptBASE64(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return encryptBASE64(signature.sign());
}
C#的方法头如下:
public static string sign(byte[] data, string privateKey)
{
// 目的:用私钥privateKey对data进行签名,并得到签名后的字符串,和java签名的方法得到一样的结果
//C# 实现DSA签名 得到一个签名后的字符串
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
}
msdn我看了,还是不知道如何使用已知的私钥。
感谢楼上这位兄弟的关注
privatestaticBoolean isValid(String xiString,String xiSig)
{
AsnKeyParser keyParser =newAsnKeyParser("path/to/key.public");
DSAParameters publicKey = keyParser.ParseDSAPublicKey();
DSACryptoServiceProvider DSA =newDSACryptoServiceProvider();
DSA.ImportParameters(publicKey);
DSASignatureDeformatterDSADeformatter=newDSASignatureDeformatter(DSA);
UTF8Encoding UTF8 =new UTF8Encoding();
byte[] plainBytes = UTF8.GetBytes(xiString);
var sha1 =new SHA1Managed();
var hash = sha1.ComputeHash(plainBytes);
byte[] asn1SigBytes =Convert.FromBase64String(xiSig);
byte[] sigBytes =ConvertToP1363Signature(asn1SigBytes);
Boolean retVal =DSADeformatter.VerifySignature(hash, sigBytes);
return retVal;
}
privatestaticbyte[]ConvertToP1363Signature(byte[] ASN1Sig)
{
AsnParser asn =newAsnParser(ASN1Sig);
asn.NextSequence();
byte[] r = asn.NextInteger();
byte[] s = asn.NextInteger();
// Returned to caller
byte[] p1363Signature =newbyte[40];
if(r.Length>21||(r.Length==21&& r[0]!=0))
{
// WTF???
// Reject - signature verification failed
}
elseif(r.Length==21)
{
// r[0] = 0
// r[1]'s high bit *should* be set
Array.Copy(r,1, p1363Signature,0,20);
}
elseif(r.Length==20)
{
// r[0]'s high bit *should not* be set
Array.Copy(r,0, p1363Signature,0,20);
}
else
{
// fewer than 20 bytes
int len = r.Length;
int off =20- len;
Array.Copy(r,0, p1363Signature, off, len);
}
if(s.Length>21||(s.Length==21&& s[0]!=0))
{
// WTF???
// Reject - signature verification failed
}
elseif(s.Length==21)
{
// s[0] = 0
// s[1]'s high bit *should* be set
Array.Copy(s,1, p1363Signature,20,20);
}
elseif(s.Length==20)
{
// s[0]'s high bit *should not* be set
Array.Copy(s,0, p1363Signature,20,20);
}
else
{
// fewer than 20 bytes
int len = s.Length;
int off =40- len;
Array.Copy(s,0, p1363Signature, off, len);
}
return p1363Signature;
}
这个AsnParser是哪里的呢