// D5puPvS6GzfOsdaW6Kjwle63AUeLFVVc
        private void SetSn(IntPtr m_Handle, string codeStr)
        {
            int resLen = 256;

            byte[] res = new byte[resLen];
            int    v   = YouyiSdk.M_GetDevSn(m_Handle, ref resLen, ref res[0]);

            if (v == 0)
            {
                byte[] sec    = new UTF8Encoding().GetBytes(BaseConfig.AC_SECRET);
                byte[] newRes = new byte[resLen];
                Array.Copy(res, newRes, resLen);
                LogHelper.ShowLog("设备SN:{0}", new UTF8Encoding().GetString(Hex.Encode(newRes)));
                // 验证激活码与SN
                byte[] md   = new byte[32];
                byte[] code = Encoding.Default.GetBytes(codeStr);
                byte[] bt   = new byte[resLen + sec.Length + code.Length];
                newRes.CopyTo(bt, 0);
                sec.CopyTo(bt, newRes.Length);
                code.CopyTo(bt, bt.Length - code.Length);

                SM3Digest sm3 = new SM3Digest();
                sm3.BlockUpdate(bt, 0, bt.Length);
                sm3.DoFinal(md, 0);
                string s = new UTF8Encoding().GetString(Hex.Encode(md));
                LogHelper.ShowLog("摘要加密:{0} 长度:{1}", s.ToUpper(), s.Length);

                YouyiSdk.M_SetUserData(m_Handle, md.Length, ref md[0]);
            }
        }
Beispiel #2
0
 public virtual void Dofinal(byte[] c3)
 {
     byte[] p = p2.Normalize().YCoord.ToBigInteger().ToByteArray();
     sm3c3.BlockUpdate(p, 0, p.Length);
     sm3c3.DoFinal(c3, 0);
     Reset();
 }
Beispiel #3
0
        /// <summary>
        /// 数字签名算法
        /// 利用自己的公私钥生成rs并存入文件
        /// </summary>
        /// <param name="sm2">sm2对象</param>
        /// <param name="pripk">自己的私钥文件夹</param>
        /// <param name="ppk">自己的公钥文件路径</param>
        /// <param name="ida">用户名</param>
        public string Test_sm2_sign(SM2 sm2, string pripk, string ppk, string ida)
        {
            BigInteger test_d = null;
            ECPoint    test_p = null;

            byte[] key = null;

            //读取私钥
            Readprikey(out test_d, pripk);
            //读取公钥
            ReadpublicKey(out key, ppk);
            test_p = sm2.ecc_curve.DecodePoint(key);

            Com.Itrus.Crypto.SM2.SM2Result sm2Ret = new Com.Itrus.Crypto.SM2.SM2Result();//实例化一个SM2Result的对象sm2Ret
            SM3Digest sm3 = new SM3Digest();

            byte[] z = sm2.Sm2GetZ(Encoding.Default.GetBytes(ida), test_p);//调用Sm2GetZ方法求a的Z的字节数组

            sm3.BlockUpdate(z, 0, z.Length);

            byte[] md = new byte[32];
            sm3.DoFinal(md, 0);
            sm2.Sm2Sign(md, test_d, test_p, sm2Ret);          //生成rs
            Writers(sm2Ret.r, sm2Ret.s, ida + "rs" + ".txt"); //写入rs文件

            return(byteToHexStr(z));
        }
Beispiel #4
0
 public void DoFinal(byte[] c3)
 {
     byte[] array = ByteConvert32Bytes(_p2.Normalize().YCoord.ToBigInteger());
     _sm3C3.BlockUpdate(array, 0, array.Length);
     _sm3C3.DoFinal(c3, 0);
     Reset();
 }
Beispiel #5
0
        /// <summary>
        /// 签名验证算法
        /// 利用签名者的公钥和传过来的r,s来验证签名是否合法
        /// </summary>
        /// <param name="sm2">sm2对象</param>
        /// <param name="ppk">签名者的公钥16进制字符串</param>
        /// <param name="Z">签名算法产生的16进制字符串 Z</param>
        /// <param name="r">签名算法生成的 R</param>
        /// <param name="s">签名算法生成的 S</param>
        /// <returns></returns>
        public bool Signature_Check(SM2 sm2, string ppk, string Z, string r, string s)
        {
            ECPoint test_p = null;

            //test_p = sm2.userKey;
            //MessageBox.Show(ppk);
            byte[] key = strToToHexByte(ppk);

            test_p = sm2.ecc_curve.DecodePoint(key);
            Com.Itrus.Crypto.SM2.SM2Result sm2Ret = new Com.Itrus.Crypto.SM2.SM2Result();//实例化一个SM2Result的对象sm2Ret
            SM3Digest sm3 = new SM3Digest();

            byte[] z = strToToHexByte(Z);
            sm3.BlockUpdate(z, 0, z.Length);
            byte[] md = new byte[32];
            sm3.DoFinal(md, 0);

            sm2Ret.r = new BigInteger(r, 16);
            sm2Ret.s = new BigInteger(s, 16);
            sm2.Sm2Verify(md, test_p, sm2Ret.r, sm2Ret.s, sm2Ret); //调用Sm2Verify方法,得到R

            if (sm2Ret.r.Equals(sm2Ret.R))                         //如果r==R
            {
                return(true);                                      //System.Console.Out.WriteLine("\n签名结果验证通过!r == R\n");
            }
            else//r!=R
            {
                return(false);//System.Console.Out.WriteLine("\n签名结果验证失败!r != R\n");
            }
        }
        public static byte[] SM3Digest(byte[] srcBytes)
        {
            SM3Digest sm3 = new SM3Digest();

            sm3.BlockUpdate(srcBytes, 0, srcBytes.Length);
            byte[] res = new byte[32];
            sm3.DoFinal(res, 0);
            return(res);
        }
Beispiel #7
0
        /**
         * 计算hash值,在数据量不大时使用,数据量大应使用原生接口,分段计算sm3值
         * @param srcData 待计算hash值的数据
         * @return
         */
        public static byte[] Hash(byte[] srcData)
        {
            SM3Digest digest = new SM3Digest();

            digest.BlockUpdate(srcData, 0, srcData.Length);
            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);
            return(hash);
        }
Beispiel #8
0
        private void NextKey()
        {
            SM3Digest sM3Digest = new SM3Digest(_sm3KeyBase);

            sM3Digest.Update((byte)((_ct >> 24) & 0xFF));
            sM3Digest.Update((byte)((_ct >> 16) & 0xFF));
            sM3Digest.Update((byte)((_ct >> 8) & 0xFF));
            sM3Digest.Update((byte)(_ct & 0xFF));
            sM3Digest.DoFinal(_key, 0);
            _keyOff = 0;
            _ct++;
        }
Beispiel #9
0
        private void NextKey()
        {
            SM3Digest sm3keycur = new SM3Digest(sm3keybase);

            sm3keycur.Update((byte)(ct >> 24 & 0x00ff));
            sm3keycur.Update((byte)(ct >> 16 & 0x00ff));
            sm3keycur.Update((byte)(ct >> 8 & 0x00ff));
            sm3keycur.Update((byte)(ct & 0x00ff));
            sm3keycur.DoFinal(key, 0);
            keyOff = 0;
            ct++;
        }
Beispiel #10
0
        public void DigestTest()
        {
            SM3Digest sm3Digest = new SM3Digest();

            string ofdXml = Path.Combine(Directory.GetCurrentDirectory(), "Files", "OFD.xml");

            byte[] ofdXmlContent = File.ReadAllBytes(ofdXml);

            sm3Digest.BlockUpdate(ofdXmlContent, 0, ofdXmlContent.Length);
            byte[] output = new byte[32];
            sm3Digest.DoFinal(output, 0);

            byte[] expect = Convert.FromBase64String("/Ew+hIIgEQwmbW71cvPmIjkT9S7ABpRZTUPHtNBwhZg=");
            Assert.AreEqual(true, Arrays.AreEqual(output, expect));
        }
Beispiel #11
0
        /// <summary>
        /// 获取杂凑值H
        /// </summary>
        /// <param name="z">Z值</param>
        /// <param name="data">待签名消息</param>
        /// <returns></returns>
        public virtual byte[] Sm2GetH(byte[] z, byte[] data)
        {
            SM3Digest sm3 = new SM3Digest();

            //Z
            sm3.BlockUpdate(z, 0, z.Length);

            //待签名消息
            sm3.BlockUpdate(data, 0, data.Length);

            // H
            byte[] md = new byte[sm3.GetDigestSize()];
            sm3.DoFinal(md, 0);

            return(md);
        }
Beispiel #12
0
        /// <summary>
        /// 签名数据验证
        /// </summary>
        /// <param name="type">电子签名类型</param>
        /// <param name="tbsContent">待签章内容</param>
        /// <param name="signedValue">电子签章数据或签名值(SignedValue.xml文件内容)</param>
        public override VerifyResult Validate(SigType type, byte[] tbsContent, byte[] signedValue)
        {
            if (type == SigType.Sign)
            {
                throw new ArgumentOutOfRangeException(nameof(type), "签名类型(type)必须是 Seal,不支持电子印章验证");
            }
            //计算原文摘要
            SM3Digest md = new SM3Digest();

            md.BlockUpdate(tbsContent, 0, tbsContent.Length);
            byte[] output = new byte[32];
            md.DoFinal(output, 0);

            SesSignature sesSignature = SesSignature.GetInstance(signedValue);
            TbsSign      toSign       = sesSignature.TbsSign;

            byte[] exceptHash = toSign.DataHash.GetOctets();
            if (!Arrays.AreEqual(output, exceptHash))
            {
                return(VerifyResult.SignedNotMatch);
            }
            //加载证书
            byte[] certDer = sesSignature.Cert.GetOctets();
            X509CertificateParser parser = new X509CertificateParser();
            X509Certificate       cert   = parser.ReadCertificate(certDer);

            //判断证书是否过期
            if (!cert.IsValid(DateTime.Now))
            {
                return(VerifyResult.SealOutdated);
            }
            //获取签名验证对象
            ISigner signer           = SignerUtilities.GetSigner(sesSignature.SignatureAlgId);
            AsymmetricKeyParameter p = cert.GetPublicKey();

            signer.Init(false, p);
            byte[] buf = toSign.GetDerEncoded();
            signer.BlockUpdate(buf, 0, buf.Length);

            //预期的电子签章数据,签章值
            byte[] expect = sesSignature.Signature.GetOctets();

            //验证签名
            bool result = signer.VerifySignature(expect);

            return(result ? VerifyResult.Success : VerifyResult.SealTampered);
        }
        public override VerifyResult Validate(SigType type, byte[] tbsContent, byte[] signedValue)
        {
            if (type == SigType.Sign)
            {
                throw new ArgumentOutOfRangeException(nameof(type), "签名类型(type)必须是 Seal,不支持电子印章验证");
            }

            // 计算原文摘要
            GeneralDigest md = new SM3Digest();

            md.BlockUpdate(tbsContent, 0, tbsContent.Length);
            byte[] expect = new byte[32];
            md.DoFinal(expect, 0);

            SesSignature sesSignature = SesSignature.GetInstance(signedValue);
            TbsSign      toSign       = sesSignature.ToSign;

            byte[] expectDataHash = toSign.DataHash.GetOctets();

            // 比较原文摘要
            if (!Arrays.AreEqual(expect, expectDataHash))
            {
                return(VerifyResult.SignedTampered);
            }

            // 预期的电子签章数据,签章值
            byte[]  expSigVal = sesSignature.Signature.GetOctets();
            ISigner sg        = SignerUtilities.GetSigner(toSign.SignatureAlgorithm);

            byte[] certDer = toSign.Cert.GetOctets();

            // 构造证书对象
            X509Certificate        x509Certificate = new X509CertificateParser().ReadCertificate(certDer);
            AsymmetricKeyParameter p = x509Certificate.GetPublicKey();

            sg.Init(false, p);

            byte[] input = toSign.GetDerEncoded();
            sg.BlockUpdate(input, 0, input.Length);

            if (!sg.VerifySignature(expSigVal))
            {
                return(VerifyResult.SignedTampered);
            }
            return(VerifyResult.Success);
        }
        private void ValiCode(object sender, EventArgs e)
        {
            string codeStr = _ActivationCode;
            int    resLen  = 256;

            byte[] res = new byte[resLen];
            int    v   = YouyiSdk.M_GetDevSn(_globalParam.m_Handle, ref resLen, ref res[0]);

            if (v == 0)
            {
                byte[] sec    = new UTF8Encoding().GetBytes(BaseConfig.AC_SECRET);
                byte[] newRes = new byte[resLen];
                Array.Copy(res, newRes, resLen);
                LogHelper.ShowLog("设备SN:{0}", new UTF8Encoding().GetString(Hex.Encode(newRes)));
                // 验证激活码与SN
                byte[] md   = new byte[32];
                byte[] code = Encoding.Default.GetBytes(codeStr);
                byte[] bt   = new byte[resLen + sec.Length + code.Length];
                newRes.CopyTo(bt, 0);
                sec.CopyTo(bt, newRes.Length);
                code.CopyTo(bt, bt.Length - code.Length);

                SM3Digest sm3 = new SM3Digest();
                sm3.BlockUpdate(bt, 0, bt.Length);
                sm3.DoFinal(md, 0);
                //string s = new UTF8Encoding().GetString(Hex.Encode(md));
                //LogHelper.ShowLog("摘要加密:{0} 长度:{1}", s.ToUpper(), s.Length);

                // 验证自定义数据
                int vali = YouyiSdk.M_VerifyUserData(_globalParam.m_Handle, md.Length, ref md[0]);
                LogHelper.ShowLog("验证结果:{0}", vali);
                Loading = false;
                if (vali != 0)
                {
                    // 失败信息
                    MessageBox.Show("卡密不正确,请联系客服处理!");
                    _window.DelegeteShutDown();
                }
                else
                {
                    // 写入激活码
                    INIHelper.Write("Info", "ActivationCode", codeStr, BaseConfig.CONFIG_PATH);
                    _window.DelegeteClose();
                }
            }
        }
Beispiel #15
0
        // codeStr:D5puPvS6GzfOsdaW6Kjwle63AUeLFVVc
        private void ValiCode(IntPtr m_Handle, string codeStr)
        {
            int resLen = 256;

            byte[] res = new byte[resLen];
            int    v   = YouyiSdk.M_GetDevSn(m_Handle, ref resLen, ref res[0]);

            if (v == 0)
            {
                byte[] sec    = new UTF8Encoding().GetBytes(BaseConfig.AC_SECRET);
                byte[] newRes = new byte[resLen];
                Array.Copy(res, newRes, resLen);
                LogHelper.ShowLog("设备SN:{0}", new UTF8Encoding().GetString(Hex.Encode(newRes)));
                // 验证激活码与SN
                byte[] md   = new byte[32];
                byte[] code = Encoding.Default.GetBytes(codeStr);
                byte[] bt   = new byte[resLen + sec.Length + code.Length];
                newRes.CopyTo(bt, 0);
                sec.CopyTo(bt, newRes.Length);
                code.CopyTo(bt, bt.Length - code.Length);

                SM3Digest sm3 = new SM3Digest();
                sm3.BlockUpdate(bt, 0, bt.Length);
                sm3.DoFinal(md, 0);

                // 验证自定义数据
                int vali = YouyiSdk.M_VerifyUserData(m_Handle, md.Length, ref md[0]);
                LogHelper.ShowLog("验证结果:{0}", vali);
                if (vali != 0)
                {
                    _valiCode += 1;
                }
                else
                {
                    if (_valiCode != 0)
                    {
                        _valiCode = 0;
                    }
                }
            }
            else
            {
                _valiCode += 1;
            }
        }
Beispiel #16
0
 /// <summary>
 /// Hash the raw data with signatureAlgorithm
 /// </summary>
 /// <param name="raw">hashing data</param>
 /// <param name="signatureAlgorithm">the autograph method</param>
 /// <returns>hashed bytes</returns>
 public static byte[] Hash(byte[] raw, string signatureAlgorithm)
 {
     if (signatureAlgorithm == "ACS3-HMAC-SHA256" || signatureAlgorithm == "ACS3-RSA-SHA256")
     {
         byte[] signData;
         using (SHA256 sha256 = new SHA256Managed())
         {
             signData = sha256.ComputeHash(raw);
         }
         return(signData);
     }
     else if (signatureAlgorithm == "ACS3-HMAC-SM3")
     {
         byte[]    md  = new byte[32];
         SM3Digest sm3 = new SM3Digest();
         sm3.BlockUpdate(raw, 0, raw.Length);
         sm3.DoFinal(md, 0);
         return(md);
     }
     return(null);
 }
Beispiel #17
0
        public virtual byte[] Sm2GetZ(byte[] userId, ECPoint userKey)
        {
            SM3Digest sm3 = new SM3Digest();

            byte[] p;
                        // userId length
                        int len = userId.Length * 8;

            sm3.Update((byte)(len >> 8 & 0x00ff));
            sm3.Update((byte)(len & 0x00ff));

            // userId
            sm3.BlockUpdate(userId, 0, userId.Length);

            // a,b
            p = ecc_a.ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);
            p = ecc_b.ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);
                        // gx,gy
                            p = ecc_gx.ToByteArray();

            sm3.BlockUpdate(p, 0, p.Length);
            p = ecc_gy.ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);

            // x,y
            p = userKey.AffineXCoord.ToBigInteger().ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);
            p = userKey.AffineYCoord.ToBigInteger().ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);

            // Z
            byte[] md = new byte[sm3.GetDigestSize()];
            sm3.DoFinal(md, 0);

            return(md);
        }
Beispiel #18
0
        /// <summary>
        /// 获取Z值
        /// Z=SM3(ENTL∣∣userId∣∣a∣∣b∣∣gx∣∣gy ∣∣x∣∣y)
        /// </summary>
        /// <param name="userId">签名方的用户身份标识</param>
        /// <param name="userKey">签名方公钥</param>
        /// <returns></returns>
        public virtual byte[] Sm2GetZ(byte[] userId, ECPoint userKey)
        {
            SM3Digest sm3 = new SM3Digest();

            byte[] p;
            // ENTL由2个字节标识的ID的比特长度
            int len = userId.Length * 8;

            sm3.Update((byte)(len >> 8 & 0x00ff));
            sm3.Update((byte)(len & 0x00ff));

            // userId用户身份标识ID
            sm3.BlockUpdate(userId, 0, userId.Length);

            // a,b为系统曲线参数;
            p = EccA.ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);
            p = EccB.ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);
            //  gx、gy为基点
            p = EccGx.ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);
            p = EccGy.ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);

            // x,y用户的公钥的X和Y
            p = userKey.Normalize().XCoord.ToBigInteger().ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);
            p = userKey.Normalize().YCoord.ToBigInteger().ToByteArray();
            sm3.BlockUpdate(p, 0, p.Length);

            // Z
            byte[] md = new byte[sm3.GetDigestSize()];
            sm3.DoFinal(md, 0);

            return(md);
        }
Beispiel #19
0
 protected override byte[] HashFinal()
 {
     _digest.DoFinal(HashValue, 0);
     return(HashValue);
 }
Beispiel #20
0
        public override void Validate(SigType type, string signAlgName, byte[] tbsContent, byte[] signedValue)
        {
            if (type == SigType.Sign)
            {
                throw new ArgumentOutOfRangeException(nameof(type), "签名类型(type)必须是 Seal,不支持电子印章验证");
            }



            // 计算原文摘要
            GeneralDigest md = new SM3Digest();

            md.BlockUpdate(tbsContent, 0, tbsContent.Length);
            byte[] expect = new byte[32];
            md.DoFinal(expect, 0);

            SesSignature sesSignature = SesSignature.GetInstance(signedValue);
            TbsSign      toSign       = sesSignature.ToSign;

            byte[] expectDataHash = toSign.DataHash.GetOctets();


            // 比较原文摘要
            if (!Arrays.AreEqual(expect, expectDataHash))
            {
                //throw new InvalidSignedValueException("Signature.xml 文件被篡改,电子签章失效。("+ toSign.getPropertyInfo().getString() + ")");
            }

            //sg.initVerify(signCert);
            //sg.update(toSign.getEncoded("DER"));
            //if (!sg.verify(expSigVal))
            //{
            //    throw new InvalidSignedValueException("电子签章数据签名值不匹配,电子签章数据失效。");
            //}

            // 预期的电子签章数据,签章值
            byte[] expSigVal = sesSignature.Signature.GetOctets();

            //Signature sg = Signature(toSign.getSignatureAlgorithm().getId(),new BouncyCastleProvider());
            ISigner sg = SignerUtilities.GetSigner(GMObjectIdentifiers.sm2encrypt_with_sm3);

            byte[] certDER = toSign.Cert.GetOctets();

            //new  X509V1CertificateGenerator().Generate()

            // 构造证书对象
            //Certificate signCert = new CertificateFactory().engineGenerateCertificate(new ByteArrayInputStream(certDER));
            //X509Certificate x509Certificate = new X509Certificate(new X509CertificateStructure(TbsCertificateStructure.GetInstance(certDER), null, new DerBitString(certDER)));
            X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(certDER);
            //x509Certificate.Verify();
            AsymmetricKeyParameter p = x509Certificate.GetPublicKey();

            sg.Init(false, p);

            //System.Security.Cryptography.X509Certificates.X509Certificate x509 = new System.Security.Cryptography.X509Certificates.X509Certificate(certDER);
            //sg.Init(false,new ECPublicKeyParameters());


            // 获取一条SM2曲线参数
            X9ECParameters sm2EcParameters = GMNamedCurves.GetByName("sm2p256v1");
            // 构造domain参数
            ECDomainParameters domainParameters = new ECDomainParameters(sm2EcParameters.Curve, sm2EcParameters.G, sm2EcParameters.N);
            //提取公钥点
            ECPoint pukPoint = sm2EcParameters.Curve.DecodePoint(certDER);
            // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04
            ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

            sg.Init(false, publicKeyParameters);


            byte[] input = toSign.GetDerEncoded();
            sg.BlockUpdate(input, 0, input.Length);

            bool pass = sg.VerifySignature(expSigVal);

            if (!pass)
            {
                throw new Exception();
            }
        }