コード例 #1
0
ファイル: Cipher.cs プロジェクト: vulild/Vulild.Core
        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++;
        }
        /// <summary>
        /// SM3加密
        /// <para>
        /// SM3是中华人民共和国政府采用的一种密码散列函数标准,由国家密码管理局于2010年12月17日发布。相关标准为“GM/T 0004-2012 《SM3密码杂凑算法》”。
        /// 在商用密码体系中,SM3主要用于数字签名及验证、消息认证码生成及验证、随机数生成等,其算法公开。据国家密码管理局表示,其安全性及效率与SHA-256相当。
        /// </para>
        /// </summary>
        /// <param name="data">待加密的数据</param>
        /// <returns>返回SM3加密后的二进制字节数组</returns>
        public static byte[] SM3(this string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return(null);
            }
            var digest = new SM3Digest();
            var bytes  = Encoding.UTF8.GetBytes(data);

            digest.BlockUpdate(bytes, 0, bytes.Length);
            return(DigestUtilities.DoFinal(digest));
        }
コード例 #3
0
        private void Reset()
        {
            this.sm3keybase = new SM3Digest();
            this.sm3c3      = new SM3Digest();

            byte[] p = byteConvert32Bytes(p2.Normalize().XCoord.ToBigInteger());
            this.sm3keybase.BlockUpdate(p, 0, p.Length);
            this.sm3c3.BlockUpdate(p, 0, p.Length);

            p = byteConvert32Bytes(p2.Normalize().YCoord.ToBigInteger());
            this.sm3keybase.BlockUpdate(p, 0, p.Length);
            this.ct = 1;
            NextKey();
        }
コード例 #4
0
        public static string Compute(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException(nameof(data));
            }

            var digest = new SM3Digest();
            var bytes  = Encoding.UTF8.GetBytes(data);

            digest.BlockUpdate(bytes, 0, bytes.Length);
            var result = DigestUtilities.DoFinal(digest);

            return(BitConverter.ToString(result).Replace("-", "").ToLower());
        }
コード例 #5
0
ファイル: Sm3Test.cs プロジェクト: fendaq/OfdSharp
        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));
        }
コード例 #6
0
ファイル: SecurityUtil.cs プロジェクト: Fujitora0424/QR_Tool
 /// <summary>
 /// sha1
 /// </summary>
 /// <param name="dataStr"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static byte[] Sm3(string dataStr, Encoding encoding)
 {
     try
     {
         byte[]    data   = encoding.GetBytes(dataStr);
         SM3Digest digest = new SM3Digest();
         digest.BlockUpdate(data, 0, data.Length);
         byte[] result = DigestUtilities.DoFinal(digest);
         return(result);
     }
     catch
     {
         return(null);
     }
 }
コード例 #7
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);
        }
コード例 #8
0
 /// <summary>
 /// sha1
 /// </summary>
 /// <param name="dataStr"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static byte[] Sm3(string dataStr, Encoding encoding)
 {
     try
     {
         byte[]    data   = encoding.GetBytes(dataStr);
         SM3Digest digest = new SM3Digest();
         digest.BlockUpdate(data, 0, data.Length);
         byte[] result = DigestUtilities.DoFinal(digest);
         return(result);
     }
     catch (Exception e)
     {
         log.Error("sm3失败:" + e.Message);
         return(null);
     }
 }
コード例 #9
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);
        }
コード例 #10
0
        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();
                }
            }
        }
コード例 #11
0
        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);
        }
コード例 #12
0
ファイル: MainWindow.xaml.cs プロジェクト: zz80900/youyiPUBG
        // 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;
            }
        }
コード例 #13
0
ファイル: Cipher.cs プロジェクト: vulild/Vulild.Core
        private void Reset()
        {
            sm3keybase = new SM3Digest();
            sm3c3      = new SM3Digest();


            byte[] p;

            p = p2.Normalize().XCoord.ToBigInteger().ToByteArray();
            sm3keybase.BlockUpdate(p, 0, p.Length);
            sm3c3.BlockUpdate(p, 0, p.Length);


            p = p2.Normalize().YCoord.ToBigInteger().ToByteArray();
            sm3keybase.BlockUpdate(p, 0, p.Length);


            ct = 1;
            NextKey();
        }
コード例 #14
0
        public override void PerformTest()
        {
            base.PerformTest();

            SM3Digest dig = new SM3Digest();

            byte[] resBuf = new byte[dig.GetDigestSize()];

            VectorTest(dig, 10, resBuf, Hex.Decode(hexMessages[0]), Hex.Decode(digests[messages.Length]));
            VectorTest(dig, 11, resBuf, Hex.Decode(hexMessages[1]), Hex.Decode(digests[messages.Length + 1]));
            VectorTest(dig, 12, resBuf, Hex.Decode(hexMessages[2]), Hex.Decode(digests[messages.Length + 2]));
            VectorTest(dig, 13, resBuf, Hex.Decode(hexMessages[3]), Hex.Decode(digests[messages.Length + 3]));
            VectorTest(dig, 14, resBuf, Hex.Decode(hexMessages[4]), Hex.Decode(digests[messages.Length + 4]));
            VectorTest(dig, 15, resBuf, Hex.Decode(hexMessages[5]), Hex.Decode(digests[messages.Length + 5]));
            VectorTest(dig, 16, resBuf, Hex.Decode(hexMessages[6]), Hex.Decode(digests[messages.Length + 6]));
            VectorTest(dig, 17, resBuf, Hex.Decode(hexMessages[7]), Hex.Decode(digests[messages.Length + 7]));

            sixtyFourKTest(sixtyFourKdigest);
            millionATest(million_a_digest);
        }
コード例 #15
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);
 }
コード例 #16
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);
        }
コード例 #17
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);
        }
コード例 #18
0
 public SM3CryptoServiceProvider()
 {
     _digest = new SM3Digest();
 }
コード例 #19
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();
            }
        }
コード例 #20
0
ファイル: Sm3DigestTests.cs プロジェクト: yangl5619/OfdSharp
 public void Sm3DigestNoContractorTest()
 {
     SM3Digest sm3Digest = new SM3Digest();
     SM2Engine sm2       = new SM2Engine(sm3Digest);
 }