通过BouncyCastle包进行Java签名C#验签时要注意asn1编码转换
在Java中采用BouncyCastle的Jar(bcprov-jdk15on-1.58.jar)對授權數據進行簽名。因為項目的歷史原因,沒用采用更高版本jar包。簽名后,把授權數據和簽名發給C#的應用進行驗簽。由于Java端的簽名結果是由64字節組成的hex字符串,是直接拼接r||s的字節數組,沒用經過asn1編碼的。在C#應用端通過NuGet引入BouncyCastle.Crypto的版本為1.9.0.0。該庫中的對象SM2Signer自帶的驗簽方法VerifySignature的參數是需要帶asn1編碼的簽名hex字符串。因此,需要把從Java中傳來的簽名字符串先進行asn1編碼后,在傳給驗簽函數VerifySignature進行驗簽。asn1編碼互轉的方法如下:
/**
? ? ? ? ?* BC的SM3withSM2驗簽需要的rs是asn1格式的,這個方法將直接拼接r||s的字節數組轉化成asn1格式
? ? ? ? ?* @param sign in plain byte array
? ? ? ? ?* @return rs result ?asn1格式
? ? ? ? ?*/
? ? ? ? public static byte[] RsByteArrayToAsn1(byte[] sign)
? ? ? ? {
? ? ? ? ? ? if (sign.Length != 32 * 2) throw new ArgumentException("err rs. ");
? ? ? ? ? ? BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, 32));
? ? ? ? ? ? BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, 32, 32 * 2));
? ? ? ? ? ? Asn1EncodableVector v = new Asn1EncodableVector();
? ? ? ? ? ? v.Add(new DerInteger(r));
? ? ? ? ? ? v.Add(new DerInteger(s));
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return new DerSequence(v).GetEncoded("DER");
? ? ? ? ? ? }
? ? ? ? ? ? catch (IOException e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? log.Error("RsPlainByteArrayToAsn1 error: " + e.Message, e);
? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? }
? ? ? ? }
/**
? ? ? ? * BC的SM3withSM2簽名得到的結果的rs是asn1格式的,這個方法轉化成直接拼接r||s
? ? ? ? * @param rsDer rs? asn1 格式
? ? ? ? * @return sign result in plain byte array
? ? ? ? */
? ? ? ? public static byte[] RsAsn1ToByteArray(byte[] rsDer)
? ? ? ? {
? ? ? ? ? ? Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
? ? ? ? ? ? byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
? ? ? ? ? ? byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
? ? ? ? ? ? byte[] result = new byte[32 * 2];
? ? ? ? ? ? Buffer.BlockCopy(r, 0, result, 0, r.Length);
? ? ? ? ? ? Buffer.BlockCopy(s, 0, result, 32, s.Length);
? ? ? ? ? ? return result;
? ? ? ? }
總結
以上是生活随笔為你收集整理的通过BouncyCastle包进行Java签名C#验签时要注意asn1编码转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css3宽度变大动画_动画演示14种流量
- 下一篇: 移动硬盘中的文件双击显示“文件或目录损坏