精华内容
下载资源
问答
  • SM4Utils sm4 = new SM4Utils { secretKey = "datalookdatalook", iv = "NEWCAPECNEWCAPEC", }; var cipherText = sm4.Encrypt_CBC(plainText).ToUpper(); //plainText = sm4.Decrypt_CBC(cipherText); byte[]...

     

                SM4Utils sm4 = new SM4Utils { secretKey = "datalookdatalook", iv = "NEWCAPECNEWCAPEC", };
    
                var cipherText = sm4.Encrypt_CBC(plainText).ToUpper();
    
                //plainText = sm4.Decrypt_CBC(cipherText);
    
                byte[] md = new byte[32];
                byte[] msg1 = Encoding.Default.GetBytes(cipherText);
                SM3Digest sm3 = new SM3Digest();
                sm3.BlockUpdate(msg1, 0, msg1.Length);
                sm3.DoFinal(md, 0);
                var sign = new UTF8Encoding().GetString(Hex.Encode(md));
    
     
    

     

    public class Cipher {
            private int ct = 1;
    
    
            private ECPoint p2;
            private SM3Digest sm3keybase;
            private SM3Digest sm3c3;
    
    
            private byte[] key = new byte[32];
            private byte keyOff = 0;
    
    
            public Cipher() {
            }
    
    
            private void Reset() {
                sm3keybase = new SM3Digest();
                sm3c3 = new SM3Digest();
    
    
                byte[] p;
    
    
                p = p2.X.ToBigInteger().ToByteArray();
                sm3keybase.BlockUpdate(p, 0, p.Length);
                sm3c3.BlockUpdate(p, 0, p.Length);
    
    
                p = p2.Y.ToBigInteger().ToByteArray();
                sm3keybase.BlockUpdate(p, 0, p.Length);
    
    
                ct = 1;
                NextKey();
            }
    
    
            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++;
            }
    
    
            public virtual ECPoint Init_enc(SM2 sm2, ECPoint userKey) {
                BigInteger k = null;
                ECPoint c1 = null;
    
    
                AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
                ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
                ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
                k = ecpriv.D;
                c1 = ecpub.Q;
    
    
                p2 = userKey.Multiply(k);
                Reset();
    
    
                return c1;
            }
    
    
            public virtual void Encrypt(byte[] data) {
                sm3c3.BlockUpdate(data, 0, data.Length);
                for (int i = 0; i < data.Length; i++) {
                    if (keyOff == key.Length)
                        NextKey();
    
    
                    data[i] ^= key[keyOff++];
                }
            }
    
    
            public virtual void Init_dec(BigInteger userD, ECPoint c1) {
                p2 = c1.Multiply(userD);
                Reset();
            }
    
    
            public virtual void Decrypt(byte[] data) {
                for (int i = 0; i < data.Length; i++) {
                    if (keyOff == key.Length)
                        NextKey();
    
    
                    data[i] ^= key[keyOff++];
                }
                sm3c3.BlockUpdate(data, 0, data.Length);
            }
    
    
            public virtual void Dofinal(byte[] c3) {
                byte[] p = p2.Y.ToBigInteger().ToByteArray();
                sm3c3.BlockUpdate(p, 0, p.Length);
                sm3c3.DoFinal(c3, 0);
                Reset();
            }
        }
        //https://blog.csdn.net/ErErFei/article/details/50999820
        public class SM2 {
            public static SM2 Instance {
                get {
                    return new SM2();
                }
    
            }
            public static SM2 InstanceTest {
                get {
                    return new SM2();
                }
    
            }
    
            public static readonly string[] sm2_param = {
                "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF",// p,0
    			"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC",// a,1
    			"28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93",// b,2
    			"FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123",// n,3
    			"32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7",// gx,4
    			"BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0" // gy,5
    	    };
    
            public string[] ecc_param = sm2_param;
    
            public readonly BigInteger ecc_p;
            public readonly BigInteger ecc_a;
            public readonly BigInteger ecc_b;
            public readonly BigInteger ecc_n;
            public readonly BigInteger ecc_gx;
            public readonly BigInteger ecc_gy;
    
            public readonly ECCurve ecc_curve;
            public readonly ECPoint ecc_point_g;
    
            public readonly ECDomainParameters ecc_bc_spec;
    
            public readonly ECKeyPairGenerator ecc_key_pair_generator;
    
            private SM2() {
                ecc_param = sm2_param;
    
                ECFieldElement ecc_gx_fieldelement;
                ECFieldElement ecc_gy_fieldelement;
    
                ecc_p = new BigInteger(ecc_param[0], 16);
                ecc_a = new BigInteger(ecc_param[1], 16);
                ecc_b = new BigInteger(ecc_param[2], 16);
                ecc_n = new BigInteger(ecc_param[3], 16);
                ecc_gx = new BigInteger(ecc_param[4], 16);
                ecc_gy = new BigInteger(ecc_param[5], 16);
    
    
                ecc_gx_fieldelement = new FpFieldElement(ecc_p, ecc_gx);
                ecc_gy_fieldelement = new FpFieldElement(ecc_p, ecc_gy);
    
                ecc_curve = new FpCurve(ecc_p, ecc_a, ecc_b);
                ecc_point_g = new FpPoint(ecc_curve, ecc_gx_fieldelement, ecc_gy_fieldelement);
    
                ecc_bc_spec = new ECDomainParameters(ecc_curve, ecc_point_g, ecc_n);
    
                ECKeyGenerationParameters ecc_ecgenparam;
                ecc_ecgenparam = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom());
    
                ecc_key_pair_generator = new ECKeyPairGenerator();
                ecc_key_pair_generator.Init(ecc_ecgenparam);
            }
    
            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.X.ToBigInteger().ToByteArray();
                sm3.BlockUpdate(p, 0, p.Length);
                p = userKey.Y.ToBigInteger().ToByteArray();
                sm3.BlockUpdate(p, 0, p.Length);
    
                // Z
                byte[] md = new byte[sm3.GetDigestSize()];
                sm3.DoFinal(md, 0);
    
                return md;
            }
    
        }
    class SM2Utils {
            public static void GenerateKeyPair() {
                SM2 sm2 = SM2.Instance;
                AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
                ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
                ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
                BigInteger privateKey = ecpriv.D;
                ECPoint publicKey = ecpub.Q;
    
                System.Console.Out.WriteLine("公钥: " + Encoding.UTF8.GetString(Hex.Encode(publicKey.GetEncoded())).ToUpper());
                System.Console.Out.WriteLine("私钥: " + Encoding.UTF8.GetString(Hex.Encode(privateKey.ToByteArray())).ToUpper());
            }
    
            public static String Encrypt(byte[] publicKey, byte[] data) {
                if (null == publicKey || publicKey.Length == 0) {
                    return null;
                }
                if (data == null || data.Length == 0) {
                    return null;
                }
    
                byte[] source = new byte[data.Length];
                Array.Copy(data, 0, source, 0, data.Length);
    
                Cipher cipher = new Cipher();
                SM2 sm2 = SM2.Instance;
    
                ECPoint userKey = sm2.ecc_curve.DecodePoint(publicKey);
    
                ECPoint c1 = cipher.Init_enc(sm2, userKey);
                cipher.Encrypt(source);
    
                byte[] c3 = new byte[32];
                cipher.Dofinal(c3);
    
                String sc1 = Encoding.UTF8.GetString(Hex.Encode(c1.GetEncoded()));
                String sc2 = Encoding.UTF8.GetString(Hex.Encode(source));
                String sc3 = Encoding.UTF8.GetString(Hex.Encode(c3));
    
                return (sc1 + sc2 + sc3).ToUpper();
            }
    
            public static byte[] Decrypt(byte[] privateKey, byte[] encryptedData) {
                if (null == privateKey || privateKey.Length == 0) {
                    return null;
                }
                if (encryptedData == null || encryptedData.Length == 0) {
                    return null;
                }
    
                String data = Encoding.UTF8.GetString(Hex.Encode(encryptedData));
    
                byte[] c1Bytes = Hex.Decode(Encoding.UTF8.GetBytes(data.Substring(0, 130)));
                int c2Len = encryptedData.Length - 97;
                byte[] c2 = Hex.Decode(Encoding.UTF8.GetBytes(data.Substring(130, 2 * c2Len)));
                byte[] c3 = Hex.Decode(Encoding.UTF8.GetBytes(data.Substring(130 + 2 * c2Len, 64)));
    
                SM2 sm2 = SM2.Instance;
                BigInteger userD = new BigInteger(1, privateKey);
    
                ECPoint c1 = sm2.ecc_curve.DecodePoint(c1Bytes);
                Cipher cipher = new Cipher();
                cipher.Init_dec(userD, c1);
                cipher.Decrypt(c2);
                cipher.Dofinal(c3);
    
                return c2;
            }
    
            public static void test() {
    
                //GenerateKeyPair();
    
                //var cipherText = "042BE5CF9B720C88E3DC88058C6CCD243F9FD504C23EC27C774F787A53D42E2074DBD3A744C62FD484B9853A8705AE1F554FC65E6B7373AF33304037971B33F2108D07610D7EDF0B4FC7FC0480959CCD864F9D253A57587229A8B2E518E1FA5F837B3DEDD339A7BFEB1A57362E7D626D919";
                //044D206F9A8AC5D0E7FB636A4C34D5D3FCA729FFCD8A020AF79134AB69802AB7D96633EAC57DB0A5DFC73FB416116AE519D627E6D6688CB21D8E92BBFF0749CB6D03C437E0E90658CBF04A517A493F1765F202DAF2DA3C7FA7348F2B09DDC15E8A1041029AB7EC12E2E324383DEBF87E97
    
                //String plainText = "1000000722200600";
    
                String plainText = "zhumz";
                byte[] sourceData = Encoding.UTF8.GetBytes(plainText);
    
                //下面的秘钥可以使用generateKeyPair()生成的秘钥内容  
                // 国密规范正式私钥  
                String prik = "5725E6C4EB6100881F76F6D82766911B5F0096FF9D47EE39BF4278AF8B63ED49";
                // 国密规范正式公钥  
                String pubk = "045212E1AD028AC8A5C2CA1884AF2AEACABC81417728102B281D0B8E518C8C86ECC738604B694D1F697B3754C017CF8604047F67B4EBF7DC9C58BC7809C4DA2349";
    
                System.Console.Out.WriteLine("加密: ");
                String cipherText = SM2Utils.Encrypt(Hex.Decode(pubk), sourceData);
                System.Console.Out.WriteLine(cipherText);
    
    
                System.Console.Out.WriteLine("解密: ");
                plainText = Encoding.UTF8.GetString(SM2Utils.Decrypt(Hex.Decode(prik), Hex.Decode(cipherText)));
                System.Console.Out.WriteLine(plainText);
    
                Console.ReadLine();
    
            }
    
            //[STAThread]
            //public static void Main()
            //{
            //    GenerateKeyPair();
    
            //    String plainText = "ererfeiisgod";
            //    byte[] sourceData = Encoding.UTF8.GetBytes(plainText);
    
            //    //下面的秘钥可以使用generateKeyPair()生成的秘钥内容  
            //    // 国密规范正式私钥  
            //    String prik = "3690655E33D5EA3D9A4AE1A1ADD766FDEA045CDEAA43A9206FB8C430CEFE0D94";
            //    // 国密规范正式公钥  
            //    String pubk = "04F6E0C3345AE42B51E06BF50B98834988D54EBC7460FE135A48171BC0629EAE205EEDE253A530608178A98F1E19BB737302813BA39ED3FA3C51639D7A20C7391A";
    
            //    System.Console.Out.WriteLine("加密: ");
            //    String cipherText = SM2Utils.Encrypt(Hex.Decode(pubk), sourceData);
            //    System.Console.Out.WriteLine(cipherText);
            //    System.Console.Out.WriteLine("解密: ");
            //    plainText = Encoding.UTF8.GetString(SM2Utils.Decrypt(Hex.Decode(prik), Hex.Decode(cipherText)));
            //    System.Console.Out.WriteLine(plainText);
    
            //    Console.ReadLine();
            //}
        }
        public abstract class GeneralDigest : IDigest {
            private const int BYTE_LENGTH = 64;
    
            private byte[] xBuf;
            private int xBufOff;
    
            private long byteCount;
    
            internal GeneralDigest() {
                xBuf = new byte[4];
            }
    
            internal GeneralDigest(GeneralDigest t) {
                xBuf = new byte[t.xBuf.Length];
                Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length);
    
                xBufOff = t.xBufOff;
                byteCount = t.byteCount;
            }
    
            public void Update(byte input) {
                xBuf[xBufOff++] = input;
    
                if (xBufOff == xBuf.Length) {
                    ProcessWord(xBuf, 0);
                    xBufOff = 0;
                }
    
                byteCount++;
            }
    
            public void BlockUpdate(
                byte[] input,
                int inOff,
                int length) {
                //
                // fill the current word
                //
                while ((xBufOff != 0) && (length > 0)) {
                    Update(input[inOff]);
                    inOff++;
                    length--;
                }
    
                //
                // process whole words.
                //
                while (length > xBuf.Length) {
                    ProcessWord(input, inOff);
    
                    inOff += xBuf.Length;
                    length -= xBuf.Length;
                    byteCount += xBuf.Length;
                }
    
                //
                // load in the remainder.
                //
                while (length > 0) {
                    Update(input[inOff]);
    
                    inOff++;
                    length--;
                }
            }
    
            public void Finish() {
                long bitLength = (byteCount << 3);
    
                //
                // add the pad bytes.
                //
                Update(unchecked((byte)128));
    
                while (xBufOff != 0) Update(unchecked((byte)0));
                ProcessLength(bitLength);
                ProcessBlock();
            }
    
            public virtual void Reset() {
                byteCount = 0;
                xBufOff = 0;
                Array.Clear(xBuf, 0, xBuf.Length);
            }
    
            public int GetByteLength() {
                return BYTE_LENGTH;
            }
    
            internal abstract void ProcessWord(byte[] input, int inOff);
            internal abstract void ProcessLength(long bitLength);
            internal abstract void ProcessBlock();
            public abstract string AlgorithmName { get; }
            public abstract int GetDigestSize();
            public abstract int DoFinal(byte[] output, int outOff);
        }
    
        public class SupportClass {
            /// <summary>
            /// Performs an unsigned bitwise right shift with the specified number
            /// </summary>
            /// <param name="number">Number to operate on</param>
            /// <param name="bits">Ammount of bits to shift</param>
            /// <returns>The resulting number from the shift operation</returns>
            public static int URShift(int number, int bits) {
                if (number >= 0)
                    return number >> bits;
                else
                    return (number >> bits) + (2 << ~bits);
            }
    
            /// <summary>
            /// Performs an unsigned bitwise right shift with the specified number
            /// </summary>
            /// <param name="number">Number to operate on</param>
            /// <param name="bits">Ammount of bits to shift</param>
            /// <returns>The resulting number from the shift operation</returns>
            public static int URShift(int number, long bits) {
                return URShift(number, (int)bits);
            }
    
            /// <summary>
            /// Performs an unsigned bitwise right shift with the specified number
            /// </summary>
            /// <param name="number">Number to operate on</param>
            /// <param name="bits">Ammount of bits to shift</param>
            /// <returns>The resulting number from the shift operation</returns>
            public static long URShift(long number, int bits) {
                if (number >= 0)
                    return number >> bits;
                else
                    return (number >> bits) + (2L << ~bits);
            }
    
            /// <summary>
            /// Performs an unsigned bitwise right shift with the specified number
            /// </summary>
            /// <param name="number">Number to operate on</param>
            /// <param name="bits">Ammount of bits to shift</param>
            /// <returns>The resulting number from the shift operation</returns>
            public static long URShift(long number, long bits) {
                return URShift(number, (int)bits);
            }
    
    
        }
    
        public class SM3Digest : GeneralDigest {
            public override string AlgorithmName {
                get {
                    return "SM3";
                }
    
            }
            public override int GetDigestSize() {
                return DIGEST_LENGTH;
            }
    
            private const int DIGEST_LENGTH = 32;
    
            private static readonly int[] v0 = new int[] { 0x7380166f, 0x4914b2b9, 0x172442d7, unchecked((int)0xda8a0600), unchecked((int)0xa96f30bc), 0x163138aa, unchecked((int)0xe38dee4d), unchecked((int)0xb0fb0e4e) };
    
            private int[] v = new int[8];
            private int[] v_ = new int[8];
    
            private static readonly int[] X0 = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    
            private int[] X = new int[68];
            private int xOff;
    
            private int T_00_15 = 0x79cc4519;
            private int T_16_63 = 0x7a879d8a;
    
            public SM3Digest() {
                Reset();
            }
    
            public SM3Digest(SM3Digest t) : base(t) {
    
                Array.Copy(t.X, 0, X, 0, t.X.Length);
                xOff = t.xOff;
    
                Array.Copy(t.v, 0, v, 0, t.v.Length);
            }
    
            public override void Reset() {
                base.Reset();
    
                Array.Copy(v0, 0, v, 0, v0.Length);
    
                xOff = 0;
                Array.Copy(X0, 0, X, 0, X0.Length);
            }
    
            internal override void ProcessBlock() {
                int i;
    
                int[] ww = X;
                int[] ww_ = new int[64];
    
                for (i = 16; i < 68; i++) {
                    ww[i] = P1(ww[i - 16] ^ ww[i - 9] ^ (ROTATE(ww[i - 3], 15))) ^ (ROTATE(ww[i - 13], 7)) ^ ww[i - 6];
                }
    
                for (i = 0; i < 64; i++) {
                    ww_[i] = ww[i] ^ ww[i + 4];
                }
    
                int[] vv = v;
                int[] vv_ = v_;
    
                Array.Copy(vv, 0, vv_, 0, v0.Length);
    
                int SS1, SS2, TT1, TT2, aaa;
                for (i = 0; i < 16; i++) {
                    aaa = ROTATE(vv_[0], 12);
                    SS1 = aaa + vv_[4] + ROTATE(T_00_15, i);
                    SS1 = ROTATE(SS1, 7);
                    SS2 = SS1 ^ aaa;
    
                    TT1 = FF_00_15(vv_[0], vv_[1], vv_[2]) + vv_[3] + SS2 + ww_[i];
                    TT2 = GG_00_15(vv_[4], vv_[5], vv_[6]) + vv_[7] + SS1 + ww[i];
                    vv_[3] = vv_[2];
                    vv_[2] = ROTATE(vv_[1], 9);
                    vv_[1] = vv_[0];
                    vv_[0] = TT1;
                    vv_[7] = vv_[6];
                    vv_[6] = ROTATE(vv_[5], 19);
                    vv_[5] = vv_[4];
                    vv_[4] = P0(TT2);
                }
                for (i = 16; i < 64; i++) {
                    aaa = ROTATE(vv_[0], 12);
                    SS1 = aaa + vv_[4] + ROTATE(T_16_63, i);
                    SS1 = ROTATE(SS1, 7);
                    SS2 = SS1 ^ aaa;
    
                    TT1 = FF_16_63(vv_[0], vv_[1], vv_[2]) + vv_[3] + SS2 + ww_[i];
                    TT2 = GG_16_63(vv_[4], vv_[5], vv_[6]) + vv_[7] + SS1 + ww[i];
                    vv_[3] = vv_[2];
                    vv_[2] = ROTATE(vv_[1], 9);
                    vv_[1] = vv_[0];
                    vv_[0] = TT1;
                    vv_[7] = vv_[6];
                    vv_[6] = ROTATE(vv_[5], 19);
                    vv_[5] = vv_[4];
                    vv_[4] = P0(TT2);
                }
                for (i = 0; i < 8; i++) {
                    vv[i] ^= vv_[i];
                }
    
                // Reset
                xOff = 0;
                Array.Copy(X0, 0, X, 0, X0.Length);
            }
    
            internal override void ProcessWord(byte[] in_Renamed, int inOff) {
                int n = in_Renamed[inOff] << 24;
                n |= (in_Renamed[++inOff] & 0xff) << 16;
                n |= (in_Renamed[++inOff] & 0xff) << 8;
                n |= (in_Renamed[++inOff] & 0xff);
                X[xOff] = n;
    
                if (++xOff == 16) {
                    ProcessBlock();
                }
            }
    
            internal override void ProcessLength(long bitLength) {
                if (xOff > 14) {
                    ProcessBlock();
                }
    
                X[14] = (int)(SupportClass.URShift(bitLength, 32));
                X[15] = (int)(bitLength & unchecked((int)0xffffffff));
            }
    
            public static void IntToBigEndian(int n, byte[] bs, int off) {
                bs[off] = (byte)(SupportClass.URShift(n, 24));
                bs[++off] = (byte)(SupportClass.URShift(n, 16));
                bs[++off] = (byte)(SupportClass.URShift(n, 8));
                bs[++off] = (byte)(n);
            }
    
            public override int DoFinal(byte[] out_Renamed, int outOff) {
                Finish();
    
                for (int i = 0; i < 8; i++) {
                    IntToBigEndian(v[i], out_Renamed, outOff + i * 4);
                }
    
                Reset();
    
                return DIGEST_LENGTH;
            }
    
            private int ROTATE(int x, int n) {
                return (x << n) | (SupportClass.URShift(x, (32 - n)));
            }
    
            private int P0(int X) {
                return ((X) ^ ROTATE((X), 9) ^ ROTATE((X), 17));
            }
    
            private int P1(int X) {
                return ((X) ^ ROTATE((X), 15) ^ ROTATE((X), 23));
            }
    
            private int FF_00_15(int X, int Y, int Z) {
                return (X ^ Y ^ Z);
            }
    
            private int FF_16_63(int X, int Y, int Z) {
                return ((X & Y) | (X & Z) | (Y & Z));
            }
    
            private int GG_00_15(int X, int Y, int Z) {
                return (X ^ Y ^ Z);
            }
    
            private int GG_16_63(int X, int Y, int Z) {
                return ((X & Y) | (~X & Z));
            }
    
            //[STAThread]
            //public static void  Main()
            //{
            //    byte[] md = new byte[32];
            //    byte[] msg1 = Encoding.Default.GetBytes("ererfeiisgod");
            //    SM3Digest sm3 = new SM3Digest();
            //    sm3.BlockUpdate(msg1, 0, msg1.Length);
            //    sm3.DoFinal(md, 0);
            //    System.String s = new UTF8Encoding().GetString(Hex.Encode(md));
            //    System.Console.Out.WriteLine(s.ToUpper());
    
            //    Console.ReadLine();
            //}
        }
     public class SM4 {
            public const int SM4_ENCRYPT = 1;
            public const int SM4_DECRYPT = 0;
            private long GET_ULONG_BE(byte[] b, int i) {
                long n = (long)(b[i] & 0xff) << 24 | (long)((b[i + 1] & 0xff) << 16) | (long)((b[i + 2] & 0xff) << 8) | (long)(b[i + 3] & 0xff) & 0xffffffffL;
                return n;
            }
    
            private void PUT_ULONG_BE(long n, byte[] b, int i) {
                b[i] = (byte)(int)(0xFF & n >> 24);
                b[i + 1] = (byte)(int)(0xFF & n >> 16);
                b[i + 2] = (byte)(int)(0xFF & n >> 8);
                b[i + 3] = (byte)(int)(0xFF & n);
            }
    
            private long SHL(long x, int n) {
                return (x & 0xFFFFFFFF) << n;
            }
    
            private long ROTL(long x, int n) {
                return SHL(x, n) | x >> (32 - n);
            }
    
            private void SWAP(long[] sk, int i) {
                long t = sk[i];
                sk[i] = sk[(31 - i)];
                sk[(31 - i)] = t;
            }
    
            public byte[] SboxTable = new byte[] { (byte) 0xd6, (byte) 0x90, (byte) 0xe9, (byte) 0xfe,
                (byte) 0xcc, (byte) 0xe1, 0x3d, (byte) 0xb7, 0x16, (byte) 0xb6,
                0x14, (byte) 0xc2, 0x28, (byte) 0xfb, 0x2c, 0x05, 0x2b, 0x67,
                (byte) 0x9a, 0x76, 0x2a, (byte) 0xbe, 0x04, (byte) 0xc3,
                (byte) 0xaa, 0x44, 0x13, 0x26, 0x49, (byte) 0x86, 0x06,
                (byte) 0x99, (byte) 0x9c, 0x42, 0x50, (byte) 0xf4, (byte) 0x91,
                (byte) 0xef, (byte) 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43,
                (byte) 0xed, (byte) 0xcf, (byte) 0xac, 0x62, (byte) 0xe4,
                (byte) 0xb3, 0x1c, (byte) 0xa9, (byte) 0xc9, 0x08, (byte) 0xe8,
                (byte) 0x95, (byte) 0x80, (byte) 0xdf, (byte) 0x94, (byte) 0xfa,
                0x75, (byte) 0x8f, 0x3f, (byte) 0xa6, 0x47, 0x07, (byte) 0xa7,
                (byte) 0xfc, (byte) 0xf3, 0x73, 0x17, (byte) 0xba, (byte) 0x83,
                0x59, 0x3c, 0x19, (byte) 0xe6, (byte) 0x85, 0x4f, (byte) 0xa8,
                0x68, 0x6b, (byte) 0x81, (byte) 0xb2, 0x71, 0x64, (byte) 0xda,
                (byte) 0x8b, (byte) 0xf8, (byte) 0xeb, 0x0f, 0x4b, 0x70, 0x56,
                (byte) 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, (byte) 0xd1,
                (byte) 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, (byte) 0x87,
                (byte) 0xd4, 0x00, 0x46, 0x57, (byte) 0x9f, (byte) 0xd3, 0x27,
                0x52, 0x4c, 0x36, 0x02, (byte) 0xe7, (byte) 0xa0, (byte) 0xc4,
                (byte) 0xc8, (byte) 0x9e, (byte) 0xea, (byte) 0xbf, (byte) 0x8a,
                (byte) 0xd2, 0x40, (byte) 0xc7, 0x38, (byte) 0xb5, (byte) 0xa3,
                (byte) 0xf7, (byte) 0xf2, (byte) 0xce, (byte) 0xf9, 0x61, 0x15,
                (byte) 0xa1, (byte) 0xe0, (byte) 0xae, 0x5d, (byte) 0xa4,
                (byte) 0x9b, 0x34, 0x1a, 0x55, (byte) 0xad, (byte) 0x93, 0x32,
                0x30, (byte) 0xf5, (byte) 0x8c, (byte) 0xb1, (byte) 0xe3, 0x1d,
                (byte) 0xf6, (byte) 0xe2, 0x2e, (byte) 0x82, 0x66, (byte) 0xca,
                0x60, (byte) 0xc0, 0x29, 0x23, (byte) 0xab, 0x0d, 0x53, 0x4e, 0x6f,
                (byte) 0xd5, (byte) 0xdb, 0x37, 0x45, (byte) 0xde, (byte) 0xfd,
                (byte) 0x8e, 0x2f, 0x03, (byte) 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b,
                0x51, (byte) 0x8d, 0x1b, (byte) 0xaf, (byte) 0x92, (byte) 0xbb,
                (byte) 0xdd, (byte) 0xbc, 0x7f, 0x11, (byte) 0xd9, 0x5c, 0x41,
                0x1f, 0x10, 0x5a, (byte) 0xd8, 0x0a, (byte) 0xc1, 0x31,
                (byte) 0x88, (byte) 0xa5, (byte) 0xcd, 0x7b, (byte) 0xbd, 0x2d,
                0x74, (byte) 0xd0, 0x12, (byte) 0xb8, (byte) 0xe5, (byte) 0xb4,
                (byte) 0xb0, (byte) 0x89, 0x69, (byte) 0x97, 0x4a, 0x0c,
                (byte) 0x96, 0x77, 0x7e, 0x65, (byte) 0xb9, (byte) 0xf1, 0x09,
                (byte) 0xc5, 0x6e, (byte) 0xc6, (byte) 0x84, 0x18, (byte) 0xf0,
                0x7d, (byte) 0xec, 0x3a, (byte) 0xdc, 0x4d, 0x20, 0x79,
                (byte) 0xee, 0x5f, 0x3e, (byte) 0xd7, (byte) 0xcb, 0x39, 0x48 };
    
            public uint[] FK = { 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc };
    
            public uint[] CK = { 0x00070e15,0x1c232a31,0x383f464d,0x545b6269,
                                            0x70777e85,0x8c939aa1,0xa8afb6bd,0xc4cbd2d9,
                                            0xe0e7eef5,0xfc030a11,0x181f262d,0x343b4249,
                                            0x50575e65,0x6c737a81,0x888f969d,0xa4abb2b9,
                                            0xc0c7ced5,0xdce3eaf1,0xf8ff060d,0x141b2229,
                                            0x30373e45,0x4c535a61,0x686f767d,0x848b9299,
                                            0xa0a7aeb5,0xbcc3cad1,0xd8dfe6ed,0xf4fb0209,
                                            0x10171e25,0x2c333a41,0x484f565d,0x646b7279 };
    
            private byte sm4Sbox(byte inch) {
                int i = inch & 0xFF;
                byte retVal = SboxTable[i];
                return retVal;
            }
    
            private long sm4Lt(long ka) {
                long bb = 0L;
                long c = 0L;
                byte[] a = new byte[4];
                byte[] b = new byte[4];
                PUT_ULONG_BE(ka, a, 0);
                b[0] = sm4Sbox(a[0]);
                b[1] = sm4Sbox(a[1]);
                b[2] = sm4Sbox(a[2]);
                b[3] = sm4Sbox(a[3]);
                bb = GET_ULONG_BE(b, 0);
                c = bb ^ ROTL(bb, 2) ^ ROTL(bb, 10) ^ ROTL(bb, 18) ^ ROTL(bb, 24);
                return c;
            }
    
            private long sm4F(long x0, long x1, long x2, long x3, long rk) {
                return x0 ^ sm4Lt(x1 ^ x2 ^ x3 ^ rk);
            }
    
            private long sm4CalciRK(long ka) {
                long bb = 0L;
                long rk = 0L;
                byte[] a = new byte[4];
                byte[] b = new byte[4];
                PUT_ULONG_BE(ka, a, 0);
                b[0] = sm4Sbox(a[0]);
                b[1] = sm4Sbox(a[1]);
                b[2] = sm4Sbox(a[2]);
                b[3] = sm4Sbox(a[3]);
                bb = GET_ULONG_BE(b, 0);
                rk = bb ^ ROTL(bb, 13) ^ ROTL(bb, 23);
                return rk;
            }
    
            private void sm4_setkey(long[] SK, byte[] key) {
                long[] MK = new long[4];
                long[] k = new long[36];
                int i = 0;
                MK[0] = GET_ULONG_BE(key, 0);
                MK[1] = GET_ULONG_BE(key, 4);
                MK[2] = GET_ULONG_BE(key, 8);
                MK[3] = GET_ULONG_BE(key, 12);
                k[0] = MK[0] ^ (long)FK[0];
                k[1] = MK[1] ^ (long)FK[1];
                k[2] = MK[2] ^ (long)FK[2];
                k[3] = MK[3] ^ (long)FK[3];
                for (; i < 32; i++) {
                    k[(i + 4)] = (k[i] ^ sm4CalciRK(k[(i + 1)] ^ k[(i + 2)] ^ k[(i + 3)] ^ (long)CK[i]));
                    SK[i] = k[(i + 4)];
                }
            }
    
            private void sm4_one_round(long[] sk, byte[] input, byte[] output) {
                int i = 0;
                long[] ulbuf = new long[36];
                ulbuf[0] = GET_ULONG_BE(input, 0);
                ulbuf[1] = GET_ULONG_BE(input, 4);
                ulbuf[2] = GET_ULONG_BE(input, 8);
                ulbuf[3] = GET_ULONG_BE(input, 12);
                while (i < 32) {
                    ulbuf[(i + 4)] = sm4F(ulbuf[i], ulbuf[(i + 1)], ulbuf[(i + 2)], ulbuf[(i + 3)], sk[i]);
                    i++;
                }
                PUT_ULONG_BE(ulbuf[35], output, 0);
                PUT_ULONG_BE(ulbuf[34], output, 4);
                PUT_ULONG_BE(ulbuf[33], output, 8);
                PUT_ULONG_BE(ulbuf[32], output, 12);
            }
    
            private byte[] padding(byte[] input, int mode) {
                if (input == null) {
                    return null;
                }
    
                byte[] ret = (byte[])null;
                if (mode == SM4_ENCRYPT) {
                    int p = 16 - input.Length % 16;
                    ret = new byte[input.Length + p];
                    Array.Copy(input, 0, ret, 0, input.Length);
                    for (int i = 0; i < p; i++) {
                        ret[input.Length + i] = (byte)p;
                    }
                    return ret;
                } else {
                    int p = input[input.Length - 1];
                    if (input.Length <= p) {
                        byte[] temp = null;
                        return temp;
                    } else {
                        ret = new byte[input.Length - p];
                        Array.Copy(input, 0, ret, 0, input.Length - p);
                        return ret;
                    }
                }
                //return ret;
            }
    
            public void sm4_setkey_enc(SM4_Context ctx, byte[] key) {
                ctx.mode = SM4_ENCRYPT;
                sm4_setkey(ctx.sk, key);
            }
    
            public void sm4_setkey_dec(SM4_Context ctx, byte[] key) {
                int i = 0;
                ctx.mode = SM4_DECRYPT;
                sm4_setkey(ctx.sk, key);
                for (i = 0; i < 16; i++) {
                    SWAP(ctx.sk, i);
                }
            }
    
            public byte[] sm4_crypt_ecb(SM4_Context ctx, byte[] input) {
                if ((ctx.isPadding) && (ctx.mode == SM4_ENCRYPT)) {
                    byte[] temp = padding(input, SM4_ENCRYPT);
                    if (temp == null) {
                        return temp;
                    } else {
                        input = padding(input, SM4_ENCRYPT);
                    }
                }
    
                int length = input.Length;
                byte[] bins = new byte[length];
                Array.Copy(input, 0, bins, 0, length);
                byte[] bous = new byte[length];
                for (int i = 0; length > 0; length -= 16, i++) {
                    byte[] inBytes = new byte[16];
                    byte[] outBytes = new byte[16];
                    Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length);
                    sm4_one_round(ctx.sk, inBytes, outBytes);
                    Array.Copy(outBytes, 0, bous, i * 16, length > 16 ? 16 : length);
                }
    
                if (ctx.isPadding && ctx.mode == SM4_DECRYPT) {
                    byte[] temp = padding(bous, SM4_DECRYPT);
                    if (temp == null) {
                        return temp;
                    } else {
                        bous = padding(bous, SM4_DECRYPT);
                        return bous;
                    }
                } else {
                    return bous;
                }
            }
    
            public byte[] sm4_crypt_cbc(SM4_Context ctx, byte[] iv, byte[] input) {
                if (ctx.isPadding && ctx.mode == SM4_ENCRYPT) {
                    byte[] temp = padding(input, SM4_ENCRYPT);
                    if (temp == null) {
                        return temp;
                    } else {
                        input = padding(input, SM4_ENCRYPT);
                    }
                }
    
                int i = 0;
                int length = input.Length;
                byte[] bins = new byte[length];
                Array.Copy(input, 0, bins, 0, length);
                byte[] bous = null;
                List<byte> bousList = new List<byte>();
                if (ctx.mode == SM4_ENCRYPT) {
                    for (int j = 0; length > 0; length -= 16, j++) {
                        byte[] inBytes = new byte[16];
                        byte[] outBytes = new byte[16];
                        byte[] out1 = new byte[16];
    
                        Array.Copy(bins, j * 16, inBytes, 0, length > 16 ? 16 : length);//原代码有错,需将i * 16改为j * 16
                        for (i = 0; i < 16; i++) {
                            outBytes[i] = ((byte)(inBytes[i] ^ iv[i]));
                        }
                        sm4_one_round(ctx.sk, outBytes, out1);
                        Array.Copy(out1, 0, iv, 0, 16);
                        for (int k = 0; k < 16; k++) {
                            bousList.Add(out1[k]);
                        }
                    }
                } else {
                    byte[] temp = new byte[16];
                    for (int j = 0; length > 0; length -= 16, j++) {
                        byte[] inBytes = new byte[16];
                        byte[] outBytes = new byte[16];
                        byte[] out1 = new byte[16];
    
                        Array.Copy(bins, j * 16, inBytes, 0, length > 16 ? 16 : length);//原代码有错,需将i * 16改为j * 16
                        Array.Copy(inBytes, 0, temp, 0, 16);
                        sm4_one_round(ctx.sk, inBytes, outBytes);
                        for (i = 0; i < 16; i++) {
                            out1[i] = ((byte)(outBytes[i] ^ iv[i]));
                        }
                        Array.Copy(temp, 0, iv, 0, 16);
                        for (int k = 0; k < 16; k++) {
                            bousList.Add(out1[k]);
                        }
                    }
    
                }
    
                if (ctx.isPadding && ctx.mode == SM4_DECRYPT) {
                    byte[] temp = padding(bousList.ToArray(), SM4_DECRYPT);
                    if (temp == null) {
                        return temp;
                    } else {
                        bous = padding(bousList.ToArray(), SM4_DECRYPT);
                        return bous;
                    }
                } else {
                    return bousList.ToArray();
                }
            }
        }
        public class SM4_Context {
            public int mode;
    
            public long[] sk;
    
            public bool isPadding;
    
            public SM4_Context() {
                this.mode = 1;
                this.isPadding = true;
                this.sk = new long[32];
            }
        }
    public class SM4Utils {
            public string secretKey = "";
            public string iv = "";
            public bool hexString = false;
            public byte[] secretKeyBuff;
    
            public string Encrypt_ECB(string plainData) {
                SM4_Context ctx = new SM4_Context();
                ctx.isPadding = true;
                ctx.mode = SM4.SM4_ENCRYPT;
    
                byte[] keyBytes;
                if (hexString) {
                    keyBytes = Decode(secretKey);
                } else {
                    keyBytes = Encoding.UTF8.GetBytes(secretKey);
                }
    
                SM4 sm4 = new SM4();
                sm4.sm4_setkey_enc(ctx, keyBytes);
                byte[] encrypted = sm4.sm4_crypt_ecb(ctx, Encoding.UTF8.GetBytes(plainData));
                //return encrypted;
                string cipherText = Encoding.UTF8.GetString(Encode(encrypted));
                return cipherText;
            }
    
            public string Decrypt_ECB(string cipherText) {
                SM4_Context ctx = new SM4_Context();
                ctx.isPadding = true;
                ctx.mode = SM4.SM4_DECRYPT;
    
                byte[] keyBytes;
                if (hexString) {
                    keyBytes = Decode(secretKey);
                } else {
                    keyBytes = Encoding.UTF8.GetBytes(secretKey);
                }
    
                SM4 sm4 = new SM4();
                sm4.sm4_setkey_dec(ctx, keyBytes);
                byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Decode(cipherText));
                if (decrypted == null) {
                    return string.Empty;
                } else {
                    return Encoding.UTF8.GetString(decrypted);
                }
            }
    
            public string Encrypt_CBC(string plainData) {
                SM4_Context ctx = new SM4_Context();
                ctx.isPadding = true;
                ctx.mode = SM4.SM4_ENCRYPT;
    
                byte[] keyBytes;
                byte[] ivBytes;
                if (hexString) {
                    keyBytes = Decode(secretKey);
                    ivBytes = Decode(iv);
                } else {
                    keyBytes = Encoding.UTF8.GetBytes(secretKey);
                    ivBytes = Encoding.UTF8.GetBytes(iv);
                }
    
                SM4 sm4 = new SM4();
                sm4.sm4_setkey_enc(ctx, keyBytes);
                byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, Encoding.UTF8.GetBytes(plainData));
    
                //return Hex.Encode(encrypted);
                //return encrypted;
                string cipherText = Encoding.UTF8.GetString(Encode(encrypted));
                return cipherText;
            }
    
            public string Decrypt_CBC(string cipherData) {
                SM4_Context ctx = new SM4_Context();
                ctx.isPadding = true;
                ctx.mode = SM4.SM4_DECRYPT;
    
                byte[] keyBytes;
                byte[] ivBytes;
                if (hexString) {
                    keyBytes = Decode(secretKey);
                    ivBytes = Decode(iv);
                } else {
                    keyBytes = Encoding.UTF8.GetBytes(secretKey);
                    ivBytes = Encoding.UTF8.GetBytes(iv);
                }
    
                SM4 sm4 = new SM4();
                sm4.sm4_setkey_dec(ctx, keyBytes);
                byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, Decode(cipherData));
                if (decrypted == null) {
                    return string.Empty;
                } else {
                    return Encoding.UTF8.GetString(decrypted);
                }
                //return decrypted;
            }
    
    
            public byte[] Encode(byte[] data) {
                int off = 0;
                int length = data.Length;
    
                MemoryStream memoryStream = new MemoryStream(length * 2);
    
                for (int index = off; index < off + length; ++index) {
                    int num = (int)data[index];
                    memoryStream.WriteByte(this.encodingTable[num >> 4]);
                    memoryStream.WriteByte(this.encodingTable[num & 15]);
                }
                length = length * 2;
    
                return memoryStream.ToArray();
            }
    
    
    
    
            public byte[] Decode(string data) {
                MemoryStream memoryStream = new MemoryStream((data.Length + 1) / 2);
    
    
                int num1 = 0;
                int length = data.Length;
                while (length > 0 && Ignore(data[length - 1]))
                    --length;
                int index1 = 0;
                InitialiseDecodingTable();
                while (index1 < length) {
                    while (index1 < length && Ignore(data[index1]))
                        ++index1;
                    byte[] decodingTable1 = this.decodingTable;
                    string str1 = data;
                    int index2 = index1;
                    int index3 = index2 + 1;
                    int index4 = (int)str1[index2];
                    byte num2 = decodingTable1[index4];
                    while (index3 < length && Ignore(data[index3]))
                        ++index3;
                    byte[] decodingTable2 = this.decodingTable;
                    string str2 = data;
                    int index5 = index3;
                    index1 = index5 + 1;
                    int index6 = (int)str2[index5];
                    byte num3 = decodingTable2[index6];
                    if (((int)num2 | (int)num3) >= 128)
                        throw new IOException("invalid characters encountered in Hex data");
                    memoryStream.WriteByte((byte)((uint)num2 << 4 | (uint)num3));
                    ++num1;
                }
                // return num1;
                byte[] rst = memoryStream.ToArray();
                return memoryStream.ToArray();
            }
    
    
    
    
            public byte[] Decode(byte[] data) {
                int off = 0;
                int length = data.Length;
                MemoryStream memoryStream = new MemoryStream(length * 2);
    
                for (int index = off; index < off + length; ++index) {
                    int num = (int)data[index];
                    memoryStream.WriteByte(this.encodingTable[num >> 4]);
                    memoryStream.WriteByte(this.encodingTable[num & 15]);
                }
                length = length * 2;
    
                return memoryStream.ToArray();
    
            }
    
            protected byte[] decodingTable = new byte[128];
    
    
            public static void Fill(byte[] buf, byte b) {
                int length = buf.Length;
                while (length > 0)
                    buf[--length] = b;
            }
            protected void InitialiseDecodingTable() {
                //Arrays.Fill(this.decodingTable, byte.MaxValue);
    
                int length = this.decodingTable.Length;
                while (length > 0) {
                    this.decodingTable[--length] = byte.MaxValue;
                }
    
    
                for (int index = 0; index < this.encodingTable.Length; ++index)
                    this.decodingTable[(int)this.encodingTable[index]] = (byte)index;
                this.decodingTable[65] = this.decodingTable[97];
                this.decodingTable[66] = this.decodingTable[98];
                this.decodingTable[67] = this.decodingTable[99];
                this.decodingTable[68] = this.decodingTable[100];
                this.decodingTable[69] = this.decodingTable[101];
                this.decodingTable[70] = this.decodingTable[102];
            }
    
            protected byte[] encodingTable =
            {
                (byte) 48,
                (byte) 49,
                (byte) 50,
                (byte) 51,
                (byte) 52,
                (byte) 53,
                (byte) 54,
                (byte) 55,
                (byte) 56,
                (byte) 57,
                (byte) 97,
                (byte) 98,
                (byte) 99,
                (byte) 100,
                (byte) 101,
                (byte) 102
            };
    
            private static bool ignore(char c) {
                return c == '\n' || c == '\r' || c == '\t' || c == ' ';
            }
    
            private static bool Ignore(char c) {
                if (c != '\n' && c != '\r' && c != '\t')
                    return c == ' ';
                return true;
            }
        }

    展开全文
  • 3.2 SM3加密类(Sm3crypto) 3.3国密SM3工具类(Sm3Utils) 3.4国密相关依赖包 4.登录认证部分 4.1前端部分关键代码 4.2后端login登录认证的关键代码 4.2.1.SM2公私钥(Sm2crypto) 4.2.2国密SM2工具类(SM2...

    目录

    1.简要

    2.开发环境及工具

    3.后台密码加密部分

    3.1加密代码

    3.2 SM3加密类(Sm3crypto)

    3.3国密SM3工具类(Sm3Utils)

    3.4国密相关依赖包

    4.登录认证部分

    4.1前端部分关键代码

    4.2后端login登录认证的关键代码

    4.2.1.SM2公私钥(Sm2crypto )

    4.2.2SM2工具类(SM2Utils)

    4.2.3SM2EngineExtend类

    5.大功告成!


    1.简要

            本文结合个人实际代码,使用SM3加盐存储密码,并且使用SM2进行登录认证。主要有以下两个点需要了解:

            1.新增用户时,将明文密码通过SM3加密后再加盐(随机生成)后形成密文存储在数据库中,同时我们也要将盐存在用户表的一个字段中(用于登录时密码的校验比对)。用户修改时不需要将盐进行更新存储。

            2.登录认证时,在前端通过一个固定的公钥将账号和密码使用sm2进行加密后再传输到后端,后端通过一个固定的私钥将账号及密码进行解密,解密后的密码通过sm3加盐进行加密后与数据库中的密文进行比对认证。

            3.以下所放的代码均为关键代码,并非全部代码,但足以供大家参考实现功能。

    2.开发环境及工具

            java,idea,mybatis-plus,spring boot,vue

    3.后台密码加密部分

            后台接收到密码明文,进行加密并保存。

    3.1加密代码

            用户表(SysUser),密码字段(password),放盐的字段(salt)

            byte[] mySalt = Sm3crypto.getSalt();
            //将盐用base64转化为字符串存到数据库中
            sysUser.setSalt(Base64.getEncoder().encodeToString(mySalt));
            //用密码sm3加密后再加盐,形成新的密码
            sysUser.setPassword(Hex.toHexString(Sm3crypto.pwdSaltedHashValue(mySalt, sysUser.getPassword())));
            this.save(sysUser);

    3.2 SM3加密类(Sm3crypto)

    import cn.stylefeng.guns.core.util.Sm3Utils;
    import org.bouncycastle.crypto.digests.SM3Digest;
    import org.bouncycastle.util.encoders.Hex;
    
    import java.io.IOException;
    import java.security.SecureRandom;
    import java.util.Base64;
    
    //SM3加密
    public class Sm3crypto {
    
    
        public static byte[] getSalt(){
            /*
             * 随机生成128位的随机数
             */
            SecureRandom random = new SecureRandom();
            byte bytes1[] = new byte[16];
            random.nextBytes(bytes1);
            return bytes1;
        }
    
        public static byte[] pwdSaltedHashValue(byte[] bytes1, String passwdString) {
    
            //sm3加密密码
            try {
                passwdString = Sm3Utils.encodeSM3(passwdString);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            /*
             * 加盐:即随机数和口令组合
             */
            byte passwdbyte[]= arraycat(bytes1,passwdString.getBytes());
            //SM3计算
            SM3Digest mdDigest=new SM3Digest();
            mdDigest.update(passwdbyte,0,passwdbyte.length);
            byte[] result=new byte[mdDigest.getDigestSize()];
            mdDigest.doFinal(result, 0);
            return result;
        }
        /*
         * 拼接buf1和buf2数组
         */
        public static byte[] arraycat(byte[] buf1,byte[] buf2)
        {
    
            byte[] bufret=null;
            int len1=0;
            int len2=0;
            if(buf1!=null)
                len1=buf1.length;
            if(buf2!=null)
                len2=buf2.length;
            if(len1+len2>0)
                bufret=new byte[len1+len2];
            if(len1>0)
                System.arraycopy(buf1,0,bufret,0,len1);
            if(len2>0)
                System.arraycopy(buf2,0,bufret,len1,len2);
            return bufret;
        }
    
    
    
    }

    3.3国密SM3工具类(Sm3Utils)

    import lombok.extern.slf4j.Slf4j;
    import org.bouncycastle.util.Arrays;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    
    /**
     * 国密SM3,消息摘要(MD5)
     *
     * @author Luke
     */
    @Slf4j
    public class Sm3Utils {
    
        private static char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        public static final byte[] IV = {0x73, (byte) 0x80, 0x16, 0x6f, 0x49, 0x14, (byte) 0xb2, (byte) 0xb9, 0x17, 0x24, 0x42,
                (byte) 0xd7, (byte) 0xda, (byte) 0x8a, 0x06, 0x00, (byte) 0xa9, 0x6f, 0x30, (byte) 0xbc, (byte) 0x16, 0x31,
                0x38, (byte) 0xaa, (byte) 0xe3, (byte) 0x8d, (byte) 0xee, 0x4d, (byte) 0xb0, (byte) 0xfb, 0x0e, 0x4e};
        private static final Integer TJ_15 = Integer.valueOf("79cc4519", 16);
        private static final Integer TJ_63 = Integer.valueOf("7a879d8a", 16);
        private static final byte[] FirstPadding = {(byte) 0x80};
        private static final byte[] ZeroPadding = {(byte) 0x00};
    
        private static int T(int j) {
            if (j >= 0 && j <= 15) {
                return TJ_15.intValue();
            } else if (j >= 16 && j <= 63) {
                return TJ_63.intValue();
            } else {
                throw new RuntimeException("data invalid");
            }
        }
    
        private static Integer FF(Integer x, Integer y, Integer z, int j) {
            if (j >= 0 && j <= 15) {
                return Integer.valueOf(x.intValue() ^ y.intValue() ^ z.intValue());
            } else if (j >= 16 && j <= 63) {
                return Integer.valueOf(
                        (x.intValue() & y.intValue()) | (x.intValue() & z.intValue()) | (y.intValue() & z.intValue()));
            } else {
                throw new RuntimeException("data invalid");
            }
        }
    
        private static Integer GG(Integer x, Integer y, Integer z, int j) {
            if (j >= 0 && j <= 15) {
                return Integer.valueOf(x.intValue() ^ y.intValue() ^ z.intValue());
            } else if (j >= 16 && j <= 63) {
                return Integer.valueOf((x.intValue() & y.intValue()) | (~x.intValue() & z.intValue()));
            } else {
                throw new RuntimeException("data invalid");
            }
        }
    
        private static Integer P0(Integer x) {
            return Integer
                    .valueOf(x.intValue() ^ Integer.rotateLeft(x.intValue(), 9) ^ Integer.rotateLeft(x.intValue(), 17));
        }
    
        private static Integer P1(Integer x) {
            return Integer.valueOf(x.intValue() ^ Integer.rotateLeft(x.intValue(), 15) ^ Integer.rotateLeft(x.intValue(), 23));
        }
    
        private static byte[] padding(byte[] source) throws IOException {
            if (source.length >= 0x2000000000000000L) {
                throw new RuntimeException("src data invalid.");
            }
            long l = source.length * 8;
            long k = 448 - (l + 1) % 512;
            if (k < 0) {
                k = k + 512;
            }
            if (log.isDebugEnabled()) {
                log.debug("k = " + k);
            }
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
                baos.write(source);
                baos.write(FirstPadding);
                long i = k - 7;
                while (i > 0) {
                    baos.write(ZeroPadding);
                    i -= 8;
                }
                baos.write(long2bytes(l));
                if (log.isDebugEnabled()) {
                    log.debug("paded size = " + baos.size());
                }
                return baos.toByteArray();
            }
        }
    
        private static byte[] long2bytes(long l) {
            byte[] bytes = new byte[8];
            for (int i = 0; i < 8; i++) {
                bytes[i] = (byte) (l >>> ((7 - i) * 8));
            }
            return bytes;
        }
    
        public static String encodeSM3(String source) throws IOException {
            byte[] b = encodeSM3(source.getBytes());
            return byteToHexString(b);
        }
    
        public static byte[] encodeSM3(byte[] source) throws IOException {
            byte[] m1 = padding(source);
            int n = m1.length / (512 / 8);
            if (log.isDebugEnabled()) {
                log.debug("n = " + n);
            }
            byte[] b;
            byte[] vi = IV.clone();
            byte[] vi1 = null;
            for (int i = 0; i < n; i++) {
                b = Arrays.copyOfRange(m1, i * 64, (i + 1) * 64);
                vi1 = CF(vi, b);
                vi = vi1;
            }
            return vi1;
        }
    
        private static byte[] CF(byte[] vi, byte[] bi) throws IOException {
            int a, b, c, d, e, f, g, h;
            a = toInteger(vi, 0);
            b = toInteger(vi, 1);
            c = toInteger(vi, 2);
            d = toInteger(vi, 3);
            e = toInteger(vi, 4);
            f = toInteger(vi, 5);
            g = toInteger(vi, 6);
            h = toInteger(vi, 7);
    
            int[] w = new int[68];
            int[] w1 = new int[64];
            for (int i = 0; i < 16; i++) {
                w[i] = toInteger(bi, i);
            }
            for (int j = 16; j < 68; j++) {
                w[j] = P1(w[j - 16] ^ w[j - 9] ^ Integer.rotateLeft(w[j - 3], 15)) ^ Integer.rotateLeft(w[j - 13], 7)
                        ^ w[j - 6];
            }
            for (int j = 0; j < 64; j++) {
                w1[j] = w[j] ^ w[j + 4];
            }
            int ss1, ss2, tt1, tt2;
            for (int j = 0; j < 64; j++) {
                ss1 = Integer.rotateLeft(Integer.rotateLeft(a, 12) + e + Integer.rotateLeft(T(j), j), 7);
                ss2 = ss1 ^ Integer.rotateLeft(a, 12);
                tt1 = FF(a, b, c, j) + d + ss2 + w1[j];
                tt2 = GG(e, f, g, j) + h + ss1 + w[j];
                d = c;
                c = Integer.rotateLeft(b, 9);
                b = a;
                a = tt1;
                h = g;
                g = Integer.rotateLeft(f, 19);
                f = e;
                e = P0(tt2);
            }
            byte[] v = toByteArray(a, b, c, d, e, f, g, h);
            for (int i = 0; i < v.length; i++) {
                v[i] = (byte) (v[i] ^ vi[i]);
            }
            return v;
        }
    
        private static int toInteger(byte[] source, int index) {
            StringBuilder valueStr = new StringBuilder("");
            for (int i = 0; i < 4; i++) {
                valueStr.append(chars[(byte) ((source[index * 4 + i] & 0xF0) >> 4)]);
                valueStr.append(chars[(byte) (source[index * 4 + i] & 0x0F)]);
            }
            return Long.valueOf(valueStr.toString(), 16).intValue();
    
        }
    
        private static byte[] toByteArray(int a, int b, int c, int d, int e, int f, int g, int h) throws IOException {
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream(32);) {
                baos.write(toByteArray(a));
                baos.write(toByteArray(b));
                baos.write(toByteArray(c));
                baos.write(toByteArray(d));
                baos.write(toByteArray(e));
                baos.write(toByteArray(f));
                baos.write(toByteArray(g));
                baos.write(toByteArray(h));
                return baos.toByteArray();
            }
        }
    
        private static byte[] toByteArray(int i) {
            byte[] byteArray = new byte[4];
            byteArray[0] = (byte) (i >>> 24);
            byteArray[1] = (byte) ((i & 0xFFFFFF) >>> 16);
            byteArray[2] = (byte) ((i & 0xFFFF) >>> 8);
            byteArray[3] = (byte) (i & 0xFF);
            return byteArray;
        }
    
        private static String byteToHexString(byte[] bytes)
        {
            StringBuilder resultHexString = new StringBuilder();
            String tempStr;
            for (byte b: bytes) {
                //这里需要对b与0xff做位与运算,
                //若b为负数,强制转换将高位位扩展,导致错误,
                //故需要高位清零
                tempStr = Integer.toHexString(b & 0xff);
                //若转换后的十六进制数字只有一位,
                //则在前补"0"
                if (tempStr.length() == 1) {
                    resultHexString.append(0).append(tempStr);
                } else {
                    resultHexString.append(tempStr);
                }
            }
            return resultHexString.toString();
        }
    
        private Sm3Utils() {
        }
    }

    3.4国密相关依赖包

    <dependency>
                    <groupId>org.bouncycastle</groupId>
                    <artifactId>bcprov-jdk15on</artifactId>
                    <version>1.57</version>
                </dependency>
                <dependency>
                    <groupId>org.bouncycastle</groupId>
                    <artifactId>bcprov-ext-jdk15on</artifactId>
                    <version>1.57</version>
                </dependency>

    4.登录认证部分

    4.1前端部分关键代码

            1.npm安装国密:

    npm install --save sm-crypto

            2.vue中引用国密:

    import SMCRYPTO from "sm-crypto";

            3.在data中定义一下sm2:

    data () {
        return {
          .
          .
          .
          sm2: SMCRYPTO.sm2,
          pubKey: "自己的SM2公钥"
        }
      },

            4.登录时将账号密码使用sm2加密后传输到后台

              //账号密码使用sm2加密
              loginParams.account = this.sm2.doEncrypt(values.account, this.pubKey, 1);
              loginParams.password = this.sm2.doEncrypt(values.password, this.pubKey, 1);

    4.2后端login登录认证的关键代码

            接收到前端的账号密码后进行处理,要将账号和密码利用SM2私钥进行解密,解密后的密码需要用sm3加密再加盐进行处理后与数据库的密码密文进行比对:

            //账号解密
            account = SM2Utils.decrypt(Sm2crypto.priKey,account,1);
    
            SysUser sysUser = sysUserService.getUserByCount(account);
    
            //用户不存在,账号或密码错误
            if (ObjectUtil.isEmpty(sysUser)) {
                LogManager.me().executeLoginLog(account, LogSuccessStatusEnum.FAIL.getCode(), AuthExceptionEnum.ACCOUNT_PWD_ERROR.getMessage());
                throw new AuthException(AuthExceptionEnum.ACCOUNT_PWD_ERROR);
            }
    
    
    
            String passwordBcrypt = sysUser.getPassword();
    
            //密码解密
            password = SM2Utils.decrypt(Sm2crypto.priKey,password,1);
    
            //获取用户表的盐
            byte[] mySalt = Base64.getDecoder().decode(sysUser.getSalt());
            //用密码sm3加密后再加盐,形成新的密码
            password = Hex.toHexString(Sm3crypto.pwdSaltedHashValue(mySalt,password));
    
            //验证账号密码是否正确
            if (ObjectUtil.isEmpty(passwordBcrypt) || !password.equals(passwordBcrypt)) {
                 LogManager.me().executeLoginLog(sysUser.getAccount(),         LogSuccessStatusEnum.FAIL.getCode(), AuthExceptionEnum.ACCOUNT_PWD_ERROR.getMessage());
                throw new AuthException(AuthExceptionEnum.ACCOUNT_PWD_ERROR);
            }

    4.2.1.SM2公私钥(Sm2crypto )

    import cn.stylefeng.guns.core.sm2.SM2KeyPair;
    import cn.stylefeng.guns.core.sm2.SM2Utils;
    import org.springframework.stereotype.Component;
    
    import java.lang.reflect.Field;
    import java.util.Objects;
    
    @Component
    public class Sm2crypto {
    
        public static String pubKey = "自己的SM2公钥,与前端加密用的公钥一样";
        public static String priKey = "自己的SM2私钥";
    
    }
    

    4.2.2SM2工具类(SM2Utils)

    import lombok.extern.slf4j.Slf4j;
    import org.bouncycastle.asn1.gm.GMNamedCurves;
    import org.bouncycastle.asn1.x9.X9ECParameters;
    import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
    import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
    import org.bouncycastle.crypto.params.*;
    import org.bouncycastle.math.ec.ECPoint;
    import org.bouncycastle.util.encoders.Hex;
    
    import java.math.BigInteger;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    
    @Slf4j
    public class SM2Utils {
    
    
        /**
         * SM2加密算法
         * @param publicKey 公钥
         * @param data 待加密的数据
         * @return 密文,BC库产生的密文带由04标识符,与非BC库对接时需要去掉开头的04
         */
        public static String encrypt(String publicKey, String data){
            // 按国密排序标准加密
            return encrypt(publicKey, data, SM2EngineExtend.CIPHERMODE_NORM);
        }
    
        /**
         * SM2加密算法
         * @param publicKey 公钥
         * @param data 待加密的数据
         * @param cipherMode 密文排列方式0-C1C2C3;1-C1C3C2;
         * @return 密文,BC库产生的密文带由04标识符,与非BC库对接时需要去掉开头的04
         */
        public static String encrypt(String publicKey, String data, int cipherMode){
            // 获取一条SM2曲线参数
            X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
            // 构造ECC算法参数,曲线方程、椭圆曲线G点、大整数N
            ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
            //提取公钥点
            ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));
            // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04
            ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);
    
            SM2EngineExtend sm2Engine = new SM2EngineExtend();
            // 设置sm2为加密模式
            sm2Engine.init(true, cipherMode, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));
    
            byte[] arrayOfBytes = null;
            try {
                byte[] in = data.getBytes();
                arrayOfBytes = sm2Engine.processBlock(in, 0, in.length);
            } catch (Exception e) {
                log.error("SM2加密时出现异常:{}", e.getMessage(), e);
            }
            return Hex.toHexString(arrayOfBytes);
        }
    
        /**
         * 获取sm2密钥对
         * BC库使用的公钥=64个字节+1个字节(04标志位),BC库使用的私钥=32个字节
         * SM2秘钥的组成部分有 私钥D 、公钥X 、 公钥Y , 他们都可以用长度为64的16进制的HEX串表示,
         * <br/>SM2公钥并不是直接由X+Y表示 , 而是额外添加了一个头,当启用压缩时:公钥=有头+公钥X ,即省略了公钥Y的部分
         * @param compressed 是否压缩公钥(加密解密都使用BC库才能使用压缩)
         * @return
         */
        public static SM2KeyPair getSm2Keys(boolean compressed){
            //获取一条SM2曲线参数
            X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
            //构造domain参数
            ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
            //1.创建密钥生成器
            ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
            //2.初始化生成器,带上随机数
            try {
                keyPairGenerator.init(new ECKeyGenerationParameters(domainParameters, SecureRandom.getInstance("SHA1PRNG")));
            } catch (NoSuchAlgorithmException e) {
                log.error("生成公私钥对时出现异常:", e);
            }
            //3.生成密钥对
            AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.generateKeyPair();
            ECPublicKeyParameters publicKeyParameters = (ECPublicKeyParameters)asymmetricCipherKeyPair.getPublic();
            ECPoint ecPoint = publicKeyParameters.getQ();
            // 把公钥放入map中,默认压缩公钥
            // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥,04的时候,可以去掉前面的04
            String publicKey = Hex.toHexString(ecPoint.getEncoded(compressed));
            ECPrivateKeyParameters privateKeyParameters = (ECPrivateKeyParameters) asymmetricCipherKeyPair.getPrivate();
            BigInteger intPrivateKey = privateKeyParameters.getD();
            // 把私钥放入map中
            String privateKey = intPrivateKey.toString(16);
            return new SM2KeyPair(publicKey, privateKey);
        }
    
        /**
         * SM2解密算法
         * @param privateKey    私钥
         * @param cipherData    密文数据
         * @return
         */
        public static String decrypt(String privateKey, String cipherData) {
            // // 按国密排序标准解密
            return decrypt(privateKey, cipherData, SM2EngineExtend.CIPHERMODE_NORM);
        }
    
        /**
         * SM2解密算法
         * @param privateKey    私钥
         * @param cipherData    密文数据
         * @param cipherMode 密文排列方式0-C1C2C3;1-C1C3C2;
         * @return
         */
        public static String decrypt(String privateKey, String cipherData, int cipherMode) {
            // 使用BC库加解密时密文以04开头,传入的密文前面没有04则补上
            if (!cipherData.startsWith("04")){
                cipherData = "04" + cipherData;
            }
            byte[] cipherDataByte = Hex.decode(cipherData);
    
            //获取一条SM2曲线参数
            X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
            //构造domain参数
            ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
    
            BigInteger privateKeyD = new BigInteger(privateKey, 16);
            ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);
    
            SM2EngineExtend sm2Engine = new SM2EngineExtend();
            // 设置sm2为解密模式
            sm2Engine.init(false, cipherMode, privateKeyParameters);
    
            String result = "";
            try {
                byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
                return new String(arrayOfBytes);
            } catch (Exception e) {
                log.error("SM2解密时出现异常:{}", e.getMessage(), e);
            }
            return result;
    
        }
    
    }
    

    4.2.3SM2EngineExtend类

    
    import org.bouncycastle.crypto.CipherParameters;
    import org.bouncycastle.crypto.Digest;
    import org.bouncycastle.crypto.InvalidCipherTextException;
    import org.bouncycastle.crypto.digests.SM3Digest;
    import org.bouncycastle.crypto.params.*;
    import org.bouncycastle.math.ec.ECConstants;
    import org.bouncycastle.math.ec.ECFieldElement;
    import org.bouncycastle.math.ec.ECPoint;
    import org.bouncycastle.util.Arrays;
    import org.bouncycastle.util.BigIntegers;
    
    import java.math.BigInteger;
    import java.security.SecureRandom;
    
    public class SM2EngineExtend {
    
        private final Digest digest;
    
        /**是否为加密模式*/
        private boolean forEncryption;
        private ECKeyParameters ecKey;
        private ECDomainParameters ecParams;
        private int curveLength;
        private SecureRandom random;
        /**密文排序方式*/
        private int cipherMode;
    
        /**BC库默认排序方式-C1C2C3*/
        public static int CIPHERMODE_BC = 0;
        /**国密标准排序方式-C1C3C2*/
        public static int CIPHERMODE_NORM = 1;
    
        public SM2EngineExtend() {
            this(new SM3Digest());
        }
    
        public SM2EngineExtend(Digest digest) {
            this.digest = digest;
        }
    
        /**
         * 设置密文排序方式
         * @param cipherMode
         */
        public void setCipherMode(int cipherMode){
            this.cipherMode = cipherMode;
        }
    
        /**
         * 默认初始化方法,使用国密排序标准
         * @param forEncryption - 是否以加密模式初始化
         * @param param - 曲线参数
         */
        public void init(boolean forEncryption, CipherParameters param) {
            init(forEncryption, CIPHERMODE_NORM, param);
        }
    
        /**
         * 默认初始化方法,使用国密排序标准
         * @param forEncryption 是否以加密模式初始化
         * @param cipherMode 加密数据排列模式:1-标准排序;0-BC默认排序
         * @param param 曲线参数
         */
        public void init(boolean forEncryption, int cipherMode, CipherParameters param) {
            this.forEncryption = forEncryption;
            this.cipherMode = cipherMode;
            if (forEncryption) {
                ParametersWithRandom rParam = (ParametersWithRandom) param;
    
                ecKey = (ECKeyParameters) rParam.getParameters();
                ecParams = ecKey.getParameters();
    
                ECPoint s = ((ECPublicKeyParameters) ecKey).getQ().multiply(ecParams.getH());
                if (s.isInfinity()) {
                    throw new IllegalArgumentException("invalid key: [h]Q at infinity");
                }
    
                random = rParam.getRandom();
            } else {
                ecKey = (ECKeyParameters) param;
                ecParams = ecKey.getParameters();
            }
    
            curveLength = (ecParams.getCurve().getFieldSize() + 7) / 8;
        }
    
        /**
         * 加密或解密输入数据
         * @param in
         * @param inOff
         * @param inLen
         * @return
         * @throws InvalidCipherTextException
         */
        public byte[] processBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException {
            if (forEncryption) {
                // 加密
                return encrypt(in, inOff, inLen);
            } else {
                return decrypt(in, inOff, inLen);
            }
        }
    
        /**
         * 加密实现,根据cipherMode输出指定排列的结果,默认按标准方式排列
         * @param in
         * @param inOff
         * @param inLen
         * @return
         * @throws InvalidCipherTextException
         */
        private byte[] encrypt(byte[] in, int inOff, int inLen)
                throws InvalidCipherTextException {
            byte[] c2 = new byte[inLen];
    
            System.arraycopy(in, inOff, c2, 0, c2.length);
    
            byte[] c1;
            ECPoint kPB;
            do {
                BigInteger k = nextK();
    
                ECPoint c1P = ecParams.getG().multiply(k).normalize();
    
                c1 = c1P.getEncoded(false);
    
                kPB = ((ECPublicKeyParameters) ecKey).getQ().multiply(k).normalize();
    
                kdf(digest, kPB, c2);
            }
            while (notEncrypted(c2, in, inOff));
    
            byte[] c3 = new byte[digest.getDigestSize()];
    
            addFieldElement(digest, kPB.getAffineXCoord());
            digest.update(in, inOff, inLen);
            addFieldElement(digest, kPB.getAffineYCoord());
    
            digest.doFinal(c3, 0);
            if (cipherMode == CIPHERMODE_NORM){
                return Arrays.concatenate(c1, c3, c2);
            }
            return Arrays.concatenate(c1, c2, c3);
        }
    
        /**
         * 解密实现,默认按标准排列方式解密,解密时解出c2部分原文并校验c3部分
         * @param in
         * @param inOff
         * @param inLen
         * @return
         * @throws InvalidCipherTextException
         */
        private byte[] decrypt(byte[] in, int inOff, int inLen)
                throws InvalidCipherTextException {
            byte[] c1 = new byte[curveLength * 2 + 1];
    
            System.arraycopy(in, inOff, c1, 0, c1.length);
    
            ECPoint c1P = ecParams.getCurve().decodePoint(c1);
    
            ECPoint s = c1P.multiply(ecParams.getH());
            if (s.isInfinity()) {
                throw new InvalidCipherTextException("[h]C1 at infinity");
            }
    
            c1P = c1P.multiply(((ECPrivateKeyParameters) ecKey).getD()).normalize();
    
            byte[] c2 = new byte[inLen - c1.length - digest.getDigestSize()];
            if (cipherMode == CIPHERMODE_BC) {
                System.arraycopy(in, inOff + c1.length, c2, 0, c2.length);
            }else{
                // C1 C3 C2
                System.arraycopy(in, inOff + c1.length + digest.getDigestSize(), c2, 0, c2.length);
            }
    
            kdf(digest, c1P, c2);
    
            byte[] c3 = new byte[digest.getDigestSize()];
    
            addFieldElement(digest, c1P.getAffineXCoord());
            digest.update(c2, 0, c2.length);
            addFieldElement(digest, c1P.getAffineYCoord());
    
            digest.doFinal(c3, 0);
    
            int check = 0;
            // 检查密文输入值C3部分和由摘要生成的C3是否一致
            if (cipherMode == CIPHERMODE_BC) {
                for (int i = 0; i != c3.length; i++) {
                    check |= c3[i] ^ in[c1.length + c2.length + i];
                }
            }else{
                for (int i = 0; i != c3.length; i++) {
                    check |= c3[i] ^ in[c1.length + i];
                }
            }
    
            clearBlock(c1);
            clearBlock(c3);
    
            if (check != 0) {
                clearBlock(c2);
                throw new InvalidCipherTextException("invalid cipher text");
            }
    
            return c2;
        }
    
        private boolean notEncrypted(byte[] encData, byte[] in, int inOff) {
            for (int i = 0; i != encData.length; i++) {
                if (encData[i] != in[inOff]) {
                    return false;
                }
            }
    
            return true;
        }
    
        private void kdf(Digest digest, ECPoint c1, byte[] encData) {
            int ct = 1;
            int v = digest.getDigestSize();
    
            byte[] buf = new byte[digest.getDigestSize()];
            int off = 0;
    
            for (int i = 1; i <= ((encData.length + v - 1) / v); i++) {
                addFieldElement(digest, c1.getAffineXCoord());
                addFieldElement(digest, c1.getAffineYCoord());
                digest.update((byte) (ct >> 24));
                digest.update((byte) (ct >> 16));
                digest.update((byte) (ct >> 8));
                digest.update((byte) ct);
    
                digest.doFinal(buf, 0);
    
                if (off + buf.length < encData.length) {
                    xor(encData, buf, off, buf.length);
                } else {
                    xor(encData, buf, off, encData.length - off);
                }
    
                off += buf.length;
                ct++;
            }
        }
    
        private void xor(byte[] data, byte[] kdfOut, int dOff, int dRemaining) {
            for (int i = 0; i != dRemaining; i++) {
                data[dOff + i] ^= kdfOut[i];
            }
        }
    
        private BigInteger nextK() {
            int qBitLength = ecParams.getN().bitLength();
    
            BigInteger k;
            do {
                k = new BigInteger(qBitLength, random);
            }
            while (k.equals(ECConstants.ZERO) || k.compareTo(ecParams.getN()) >= 0);
    
            return k;
        }
    
        private void addFieldElement(Digest digest, ECFieldElement v) {
            byte[] p = BigIntegers.asUnsignedByteArray(curveLength, v.toBigInteger());
    
            digest.update(p, 0, p.length);
        }
    
        /**
         * clear possible sensitive data
         */
        private void clearBlock(
                byte[] block) {
            for (int i = 0; i != block.length; i++) {
                block[i] = 0;
            }
        }
    
    
    }
    
    
    

    5.大功告成!

    展开全文
  • SM? SM1? SM2? SM3? SM4?

    2021-02-08 08:00:00
    最近看了一个项目的代码,用到了SM2,SM3,SM4,瞬间懵逼,一会用SM2,一会用SM3,一会又用SM4,SM???简单来说,SM2,SM3,SM4 是国家密码局认定的国产密码算法,当然...

    最近看了一个项目的代码,用到了SM2,SM3,SM4,瞬间懵逼,一会用SM2,一会用SM3,一会又用SM4SM???

    简单来说,SM2,SM3,SM4 是国家密码局认定的国产密码算法,当然除了这几个算法,还有SM1,SM7,SM9,祖冲之密码算法等。

    本文重点是SM算法的Java实现,并不是研究这几种算法的原理以及和其他算法的比较等。

    这里简单介绍下这几种SM算法,先有个大概的印象:

    SM1

    它是一种对称加密算法中的分组加密算法,分组长度、秘钥长度都是128位,和国际上通用的 AES, DES一样,SM1 算法目前还没公开,只能集成在芯片中。

    SM2

    和国际上通过的RSA一样,是一种非对称加密算法,使用公钥加密,私钥解密,在安全性和运算速度方面要优于RSA算法。

    SM3

    可以用来生成信息摘要,如MD5,生成的信息摘要长度为256位。

    SM4

    是一种对称加密算法,可用于替代DES/AES等国际算法, SM4算法与AES算法具有相同的密钥长度和分组长度,都是128位。

    当然这些算法的源码可以在商用密码检测中心中下载,我已经下载好了,公众号回复【SM】即可下载。

    了解了SM2, SM3, SM4这些算法之后,在我们的系统中就可以应用这些算法来对传输的报文进行加解密;一个简单的流程图如下所示:

    SM2

    下面将来重点介绍SM2算法

    SM2算法是国家密码管理局发布的椭圆曲线公钥密码算法,推荐使用素数域256位椭圆曲线

    椭圆曲线方程:曲线参数为:如果你数学够屌,文档给你准备好了,公众号回复【SM】即可下载。

    SM2 java实现

    既然SM2算法那么厉害,接下来我们就使用Java来实现下吧。

    首先在项目中引入对应的jar包:

    <dependency>
     <groupId>org.bouncycastle</groupId>
     <artifactId>bcprov-jdk15on</artifactId>
     <version>1.60</version>
    </dependency>
    

    首先第一步,是要创建 SM2 的椭圆曲线参数,用到的类为 「SM2P256V1Curve」,它是代表国密SM2推荐参数定义的椭圆曲线,源码如下:可以看到和上面所提供的推荐参数是一样的。

    由于「SM2P256V1Curve」没有实现Gx 和 Gy,即基点G的x,y坐标,我们需要自行创建,参数为推荐的参数即可,然后使用x,y 坐标创建基点G,代码如下:第一步创建 SM2 的椭圆曲线参数的代码如下:第二步,由于SM2算法基于 ECC,所以需要根据曲线参数来生成 ECC密钥对,代码如下:第三步,通过 ECC 密钥对获取SM2公钥和私钥,代码如下:

    第四步,获取到公钥之后,就可以使用公钥对报文进行加密了,代码如下:第五步,加密之后,需要使用私钥来进行解密,代码如下:第六步,现在来测试一下吧。运行结果如下:

    到这里使用Java来实现SM2加解密算法已经结束了,是不是很简单,你学废了吗?

    完成代码如下:

    生成SM2公私钥:

    private static Map<String, ECKeyParameters> getSm2PrivateKeyOrPublicKey() {
     // P256V1Curve 代表国密SM2推荐参数定义的椭圆曲线:
     SM2P256V1Curve sm2P256V1Curve = new SM2P256V1Curve();
     BigInteger sm2N = sm2P256V1Curve.getOrder();
     BigInteger sm2H = sm2P256V1Curve.getCofactor();
     // 由于 gx,gy 没有提供,需要自己创建默认参数
     BigInteger sm2Gx = new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16);
     BigInteger sm2Gy = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16);
     // 根据 gx, gy 坐标创建一个 G点,即为椭圆的基点
     ECPoint sm2Gpoint = sm2P256V1Curve.createPoint(sm2Gx, sm2Gy);
     //设置椭圆曲线参数
     ECDomainParameters ecDomainParameters = new ECDomainParameters(sm2P256V1Curve, sm2Gpoint, sm2N, sm2H);
     // 生成ECC密钥对
     ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom());
     ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
     keyPairGenerator.init(keyGenerationParameters);
     // ECC密钥对
     AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.generateKeyPair();
     // 通过 ECC 密钥对获取SM2公钥和私钥
     // 私钥
     ECPrivateKeyParameters sm2PrivateKey = (ECPrivateKeyParameters) asymmetricCipherKeyPair.getPrivate();
     String x = ByteUtils.toHexString(sm2PrivateKey.getParameters().getG().getAffineXCoord().getEncoded());
     String y = ByteUtils.toHexString(sm2PrivateKey.getParameters().getG().getAffineYCoord().getEncoded());
     System.out.println("生成的SM2私钥为:" + x + "-" + y);
     // 公钥
     ECPublicKeyParameters sm2PublicKey = (ECPublicKeyParameters) asymmetricCipherKeyPair.getPublic();
     String x1 = ByteUtils.toHexString(sm2PublicKey.getQ().getAffineYCoord().getEncoded());
     String y1 = ByteUtils.toHexString(sm2PublicKey.getQ().getAffineXCoord().getEncoded());
     System.out.println("生成的SM2公钥为:" + x1 + "-" + y1);
    
     Map<String, ECKeyParameters> map = new HashMap<>(2);
     map.put("private", sm2PrivateKey);
     map.put("public", sm2PublicKey);
     return map;
    }
    

    加密:

    /**
     * 公钥加密
     *
     * @param sm2PublicKey SM2 公钥
     * @param pack         加密的报文
     * @return 加密后的保温
     * @throws Exception e
     */
    private static String sm2Encrypt(ECPublicKeyParameters sm2PublicKey, String pack) throws Exception {
     SM2Engine sm2PublicEngine = new SM2Engine();
     ParametersWithRandom withRandom = new ParametersWithRandom(sm2PublicKey, new SecureRandom());
     sm2PublicEngine.init(true, withRandom);
     byte[] encryResult = sm2PublicEngine.processBlock(pack.getBytes(StandardCharsets.UTF_8), 0, pack.getBytes(StandardCharsets.UTF_8).length);
     String encryResultStr = Base64.getEncoder().encodeToString(encryResult);
     System.out.println("加密后的报文为:" + encryResultStr);
     return encryResultStr;
    }
    

    解密:

    /**
     * SM2 私钥解密
     *
     * @param sm2PrivateKey SM2 私钥
     * @param pack          解密报文
     * @throws Exception e
     */
    private static void sm2Decrypt(ECPrivateKeyParameters sm2PrivateKey, String pack) throws Exception {
     SM2Engine sm2PrivateEngine = new SM2Engine();
     sm2PrivateEngine.init(false, sm2PrivateKey);
     byte[] decodePackByte = Base64.getDecoder().decode(pack);
     byte[] decryptResult = sm2PrivateEngine.processBlock(decodePackByte, 0, decodePackByte.length);
     String decryptResultStr = new String(decryptResult, StandardCharsets.UTF_8);
     System.out.println("解密后的报文为:" + decryptResultStr);
    }
    

    测试:

    static {
     Security.addProvider(new BouncyCastleProvider());
    }
    
    public static void main(String[] args) throws Exception {
     Map<String, ECKeyParameters> sm2Key = getSm2PrivateKeyOrPublicKey();
     String pack = "公众号搜索【Java技术编程】, 公众号搜索【Java技术编程】, 公众号搜索【Java技术编程】";
     System.out.println("原始报文为:" + pack);
     // 对报文进行加密
     String encryResult = sm2Encrypt((ECPublicKeyParameters) sm2Key.get("public"), pack);
     // 对报文进行解密
     sm2Decrypt((ECPrivateKeyParameters) sm2Key.get("private"), encryResult);
    }
    

    SM3 Java 实现

    下一篇,敬请期待。

    SM4 Java 实现

    下下一篇,敬请期待。

    展开全文
  • PB实现国密SM2/SM3/SM4算法(DLL方式)

    千次阅读 2021-07-04 14:18:38
    文章目录SM4SM3SM2 SM4 SM3 SM2

    SM4

    SM4简介

    SM4是一种数据分组加密算法,可以类比DES、AES等常用的分组加密算法。SM4为对称加密,分组长度和秘钥长度均为16字节。

    分组加密模式ECB与CBC

    ECB模式直接对明文的每个分块加密,流程如下图:
    在这里插入图片描述
    CBC模式将第1个分块与初始化向量IV异或运算后再加密,再将第N个分块与第N-1个分块加密值的异或运算结果进行加密,流程图如下:
    在这里插入图片描述

    ECB模式加密解密

    秘钥:
    1234567812345678

    待加密文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    加密代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    blob lblb_key, lblb_text, lblb_encrypted
    string ls_text, ls_encrypted
    
    lblb_key = blob('1234567812345678')
    
    ls_text = '1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法'
    ln_charset.to_utf8(ls_text, lblb_text)
    
    gm.sm4_ecb_encrypt( lblb_text, lblb_key, lblb_encrypted)
    ls_encrypted = code_util.base64_encode( lblb_encrypted)
    
    return 0
    
    

    在这里插入图片描述
    得到密文:
    USnxwnysSyczfnzWrouvfsXiR5dVhPcMUU6Lth/HQZHrr6ArzeRtQFlEoXEp3AFpTvAb/RFnw2WbZprFZ7AWbX4fmhc4lQSrP+94xTrn/KI=

    接下来,解密上面得到的密文
    解密代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    blob lblb_key, lblb_text, lblb_encrypted
    string ls_text, ls_encrypted
    
    lblb_key = blob('1234567812345678')
    
    ls_encrypted = 'USnxwnysSyczfnzWrouvfsXiR5dVhPcMUU6Lth/HQZHrr6ArzeRtQFlEoXEp3AFpTvAb/RFnw2WbZprFZ7AWbX4fmhc4lQSrP+94xTrn/KI='
    lblb_encrypted = code_util.base64_decode( ls_encrypted)
    
    gm.sm4_ecb_decrypt( lblb_encrypted, lblb_key, lblb_text)
    ln_charset.from_utf8(lblb_text, ls_text)
    
    return 0
    
    

    在这里插入图片描述
    得到解密后的文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    CBC模式加密解密

    秘钥:
    1234567812345678

    初始化向量IV:
    a1b2c3d4e5f6g7h8

    待加密文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    加密代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    blob lblb_key, lblb_iv, lblb_text, lblb_encrypted
    string ls_text, ls_encrypted
    
    lblb_key = blob('1234567812345678')
    lblb_iv = blob('a1b2c3d4e5f6g7h8')
    
    ls_text = '1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法'
    ln_charset.to_utf8(ls_text, lblb_text)
    
    gm.sm4_cbc_encrypt( lblb_text, lblb_key, lblb_iv, lblb_encrypted)
    ls_encrypted = code_util.base64_encode( lblb_encrypted)
    
    return 0
    
    

    在这里插入图片描述

    得到密文:
    cBpwNbKHVF0UbOwQtmeO20L+vc/YMONxtlfUfFTRZaAtcBmpZEe8AuXN5cctDn9KJ0qCjrCNntio8pRZuTDaYaQBHcdG7qXqv7iHhmOVPj8=

    接下来,解密上面得到的密文
    解密代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    blob lblb_key, lblb_iv, lblb_text, lblb_encrypted
    string ls_text, ls_encrypted
    
    lblb_key = blob('1234567812345678')
    lblb_iv = blob('a1b2c3d4e5f6g7h8')
    
    ls_encrypted = 'cBpwNbKHVF0UbOwQtmeO20L+vc/YMONxtlfUfFTRZaAtcBmpZEe8AuXN5cctDn9KJ0qCjrCNntio8pRZuTDaYaQBHcdG7qXqv7iHhmOVPj8='
    lblb_encrypted = code_util.base64_decode( ls_encrypted)
    
    gm.sm4_cbc_decrypt( lblb_encrypted, lblb_key, lblb_iv, lblb_text)
    ln_charset.from_utf8(lblb_text, ls_text)
    
    return 0
    

    在这里插入图片描述

    得到解密后的文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    SM3

    SM3简介

    SM3是一种消息摘要算法,可以类比MD5、SHA256等常用的消息摘要算法。SM3算法生成的消息摘要长度为32字节。

    SM3摘要生成

    消息文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    计算SM3摘要代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    string ls_text, ls_sm3
    blob lblb_text, lblb_sm3
    
    ls_text = '1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法'
    ln_charset.to_utf8(ls_text, lblb_text)
    
    gm.sm3_digest( lblb_text, lblb_sm3)
    ls_sm3 = code_util.hex_encode(lblb_sm3)
    
    return 0
    
    

    在这里插入图片描述
    得到SM3消息摘要:
    640BA3331EFB8B017F4B34A94B8BB7D94AA564767C031F1917C440934CFE834C

    SM3WithSM2摘要生成

    SM3WithSM2摘要算法基于SM3算法,主要是作为SM2签名算法的摘要算法使用,SM2签名算法见后文,这里先单独演示SM3WithSM2算法的使用

    公钥BASE64:
    agqV3MU7WaQCpAHHhVV8GDolxHqx3PfLbSEOhmtz1U271UjRN6j0I4D4Cn/MEpbMrl+SAsFHWwaXd5+SoLZq6Q==

    消息文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    计算SM3WithSM2摘要代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    string ls_text, ls_sm3_with_sm2
    blob lblb_text, lblb_public_key, lblb_sm3_with_sm2
    string ls_public_key
    
    ls_public_key = 'agqV3MU7WaQCpAHHhVV8GDolxHqx3PfLbSEOhmtz1U271UjRN6j0I4D4Cn/MEpbMrl+SAsFHWwaXd5+SoLZq6Q=='
    lblb_public_key = code_util.base64_decode( ls_public_key)
    
    ls_text = '1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法'
    ln_charset.to_utf8(ls_text, lblb_text)
    
    gm.sm3_with_sm2_digest( lblb_text, lblb_public_key, lblb_sm3_with_sm2)
    ls_sm3_with_sm2 = code_util.hex_encode(lblb_sm3_with_sm2)
    
    return 0
    

    在这里插入图片描述
    得到SM3WithSM2消息摘要:
    F4261292B3BE90400DB813085A3BE0329021073FF2E792CD0C2D4F2E4443EE8C

    SM2

    SM2简介

    SM2是一种非对称加密算法,包含数字签名算法和公钥加密算法,可以类比常用的RSA算法。

    SM2签名与验签

    常用签名算法签名和验签的流程如下:
    在这里插入图片描述
    签名算法需要搭配摘要算法使用,SM2签名常用的摘要算法是上文中的SM3WithSM2算法

    下面开始演示SM2签名与验签

    公钥BASE64:
    agqV3MU7WaQCpAHHhVV8GDolxHqx3PfLbSEOhmtz1U271UjRN6j0I4D4Cn/MEpbMrl+SAsFHWwaXd5+SoLZq6Q==

    私钥BASE64:
    YWJjZGVmZ2gxMjM0NTY3ODg3NjU0MzIxaGdmZWRjYmE=

    消息文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    计算SM2签名代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    string ls_text
    blob lblb_text, lblb_public_key, lblb_private_key, lblb_sign
    string ls_public_key, ls_private_key, ls_sign
    
    ls_public_key = 'agqV3MU7WaQCpAHHhVV8GDolxHqx3PfLbSEOhmtz1U271UjRN6j0I4D4Cn/MEpbMrl+SAsFHWwaXd5+SoLZq6Q=='
    ls_private_key = 'YWJjZGVmZ2gxMjM0NTY3ODg3NjU0MzIxaGdmZWRjYmE='
    lblb_public_key = code_util.base64_decode( ls_public_key)
    lblb_private_key = code_util.base64_decode( ls_private_key)
    
    ls_text = '1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法'
    ln_charset.to_utf8(ls_text, lblb_text)
    
    gm.sm2_sign_by_sm3( lblb_text, lblb_private_key, lblb_public_key, lblb_sign)
    ls_sign = code_util.base64_encode( lblb_sign)
    
    return 0
    

    在这里插入图片描述
    得到SM2签名的BASE64编码如下:
    fd9JKrBDUMrzE6xGfsfPyb0p7n9ZFyuY8meraGHwndkJU5yswlmI3UIMy2rNQTP3CG4wBaZgF5z/IqHBcdIx9Q==

    SM2签名算法的过程中有使用随机数,所以每次计算的签名值可能都不同

    下面用这个签名测试验签

    验证SM2签名代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    string ls_text
    blob lblb_text, lblb_public_key, lblb_private_key, lblb_sign
    string ls_public_key, ls_private_key, ls_sign
    long ll_verify_1, ll_verify_2
    
    ls_public_key = 'agqV3MU7WaQCpAHHhVV8GDolxHqx3PfLbSEOhmtz1U271UjRN6j0I4D4Cn/MEpbMrl+SAsFHWwaXd5+SoLZq6Q=='
    lblb_public_key = code_util.base64_decode( ls_public_key)
    
    ls_sign = 'fd9JKrBDUMrzE6xGfsfPyb0p7n9ZFyuY8meraGHwndkJU5yswlmI3UIMy2rNQTP3CG4wBaZgF5z/IqHBcdIx9Q=='
    lblb_sign = code_util.base64_decode( ls_sign)
    
    ls_text = '1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法'
    ln_charset.to_utf8(ls_text, lblb_text)
    
    ll_verify_1 = gm.sm2_verify_by_sm3( lblb_text, lblb_public_key, lblb_sign)
    
    blobedit(lblb_text, 7, char(37))
    ll_verify_2 = gm.sm2_verify_by_sm3( lblb_text, lblb_public_key, lblb_sign)
    
    return 0
    

    在这里插入图片描述
    用原始的消息和签名值验签,验签方法返回0,验签成功
    若篡改了原始的消息,验签方法返回-1,验签失败

    SM2加密与解密

    公钥BASE64:
    agqV3MU7WaQCpAHHhVV8GDolxHqx3PfLbSEOhmtz1U271UjRN6j0I4D4Cn/MEpbMrl+SAsFHWwaXd5+SoLZq6Q==

    私钥BASE64:
    YWJjZGVmZ2gxMjM0NTY3ODg3NjU0MzIxaGdmZWRjYmE=

    消息文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    SM2公钥加密代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    string ls_text
    blob lblb_text, lblb_public_key, lblb_encrypted
    string ls_public_key, ls_encrypted
    
    ls_public_key = 'agqV3MU7WaQCpAHHhVV8GDolxHqx3PfLbSEOhmtz1U271UjRN6j0I4D4Cn/MEpbMrl+SAsFHWwaXd5+SoLZq6Q=='
    lblb_public_key = code_util.base64_decode( ls_public_key)
    
    ls_text = '1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法'
    ln_charset.to_utf8(ls_text, lblb_text)
    
    gm.sm2_encrypt( lblb_text, lblb_public_key, lblb_encrypted)
    ls_encrypted = code_util.base64_encode( lblb_encrypted)
    
    return 0
    

    在这里插入图片描述
    得到SM2密文的BASE64编码如下:
    xsnyO8X2sJ2jl2sH5C3llxgNoYghqQhgd3f+em9NyXhvlF1dgba8UklF3XEk8u5STngWW431wVNm1pVsXlhIZKa7iSGcm5ez9ZMgvbAna5QjRfXvVmC2yeBuyFOi9zru5LLr9OxYjQm4x32qMRUZUlq5s5C6ChK+Qc4PFVk5iL6DrlLL2a0309xAdSUpmPupqUWYmwRE9lFtyPnqI04WblVHiBkpR64l6Y4=

    SM2加密算法的过程中有使用随机数,所以每次计算的密文可能都不同

    下面用这个密文测试解密

    SM2私钥解密代码及运行效果如下:

    n_gm gm
    n_func_charset ln_charset
    n_code_util code_util
    string ls_text
    blob lblb_text, lblb_private_key, lblb_encrypted
    string ls_private_key, ls_encrypted
    
    ls_private_key = 'YWJjZGVmZ2gxMjM0NTY3ODg3NjU0MzIxaGdmZWRjYmE='
    lblb_private_key = code_util.base64_decode( ls_private_key)
    
    ls_encrypted = 'xsnyO8X2sJ2jl2sH5C3llxgNoYghqQhgd3f+em9NyXhvlF1dgba8UklF3XEk8u5STngWW431wVNm1pVsXlhIZKa7iSGcm5ez9ZMgvbAna5QjRfXvVmC2yeBuyFOi9zru5LLr9OxYjQm4x32qMRUZUlq5s5C6ChK+Qc4PFVk5iL6DrlLL2a0309xAdSUpmPupqUWYmwRE9lFtyPnqI04WblVHiBkpR64l6Y4='
    lblb_encrypted = code_util.base64_decode( ls_encrypted)
    
    gm.sm2_decrypt( lblb_encrypted, lblb_private_key, lblb_text)
    ln_charset.from_utf8(lblb_text, ls_text)
    
    return 0
    

    在这里插入图片描述
    得到解密后的文本:
    1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法

    说明

    本文代码的测试环境为PowerBuilder Version 8.0.2 Build 9506
    项目下载

    展开全文
  • SM3算法

    2021-09-04 18:40:30
    文章目录前言一、SM3是什么?二、go语言实现 前言 提示:以下是本篇文章正文内容,下面案例可供参考 一、SM3是什么? SM3是中华人民共和国政府采用的一种密码散列函数标准,由国家密码管理局于2010年12月17日发布。...
  • SM3算法的编程实现

    2021-06-19 21:04:51
    SM3算法的编程实现SM3算法的编程实现【实验目的】【实验环境】【实验预备知识点】【实验步骤】【实验思考题】 SM3算法的编程实现 【实验目的】 1、理解Hash函数的计算原理和特点; 2、理解SM3算法原理; 3、了解SM3...
  • SM2,SM4,SM3,国密算法PHP版.rar

    千次阅读 2021-03-24 11:35:31
    Code\SoftKey.vb 15.77 KB 2016/3/17 15:13:47 24 身份认证例子(htm5)\SM2国密算法例子\JSP\testsm2_new\WebContent\com\SM2SM3.java 15.54 KB 2012/1/26 21:59:41 25 身份认证例子(htm5)\写用户名及密码工具\工具...
  • SM3算法 C语言 (从OpenSSL库中分离算法:六) OpenSSL简介: OpenSSL 是用于传输层安全性 (TLS) 和安全套接字层 (SSL) 协议的一个强大、商业级和功能齐全的工具包,它也是一个通用的密码学库。包含有RSA、SM4、DES、...
  • 主要有SM1,SM2,SM3,SM4。密钥长度和分组长度均为128位。目前主要使用公开的SM2、SM3、SM4三类算法,分别是非对称算法、哈希算法和对称算法。SM1为对称加密。其加密强度与AES相当。该算法不公开,调用该算法时,...
  • 国密算法 SM2 SM3 SM4分别用作什么

    千次阅读 2021-12-05 10:49:07
    非对称加密SM2(可选支持国内SM9)算法实现数据的签名、验签和加解密对称密钥, SM3密码杂凑算法实现数据摘要的生成, 对称密钥SM4加密算法实现对数据内容的加密。
  • javascript 实现sm3哈希算法

    千次阅读 2020-12-29 09:19:14
    javascript 实现sm3哈希算法 各位看官直接上code,随copy随食用。 分别建三个js文件: sm_utils.js var utils = exports utils.strToBytes = strToBytes function strToBytes(s) { var ch, st, re = []; ...
  • 密码学课程作业:基于Java实现国产密码算法中的哈希算法SM3Tips:本项目只做学习之用,未经全面测试和验证,不能用于实际项目中。...在SM3.java目录下打开命令行窗口,编译并运行:12javac SM3.javajava S...
  • SM3是哈希算法。 其中SM1、SM7算法不公开,调用该算法时,需要通过加密芯片的接口进行调用。 二、详述 2.1、SM1对称密码 SM1 算法是分组密码算法,分组长度为128位,密钥长度都为 128 比特,算法安全保密强度及...
  • java sm3加密算法

    千次阅读 2021-02-12 18:44:05
    1.准备工作所需jar包:bcprov-jdk15on-1.59.jarcommons-lang3-3.1.jar20200901对应的maven依赖org.bouncycastlebcprov-jdk15on1.66import org.bouncycastle.crypto.digests.SM3Digest;import org.bouncycastle....
  • 对于应用层程序员来说,必须熟悉他的使用,以及他的应用领域,一般在写一个安全的应用时,如果单单使用SM2是不安全的,基本上SM2、SM3、SM4都会同时使用。一般都是用SM4对数据内容加密,使用SM3,对内容进行摘要,再...
  • PHP实现国密SM3算法

    2021-09-15 15:53:28
    最近对接一个第三方系统,对方要求接口签名加密使用sm3加密算法,不过php没有原生支持该算法的函数,所以需要借助外力了。网上查资料发现在PHP中实现sm3算法,大概有一下三种途径:A.使用PHP的OpenSSL扩展实现 B.使用一...
  • 一、SM3算法介绍 杂凑值算法也可称为摘要算法或者哈希算法。通过对数据资料的填充、分组、扩展压缩等方式计算成特定长度的数值,来作为数据指纹或者数据特征使用。常见的MD5算法长度为128bit(16字节),SHA1算法...
  • 文章目录一、SM3算法原理二、SM3算法的C++代码实现三、SM3算法的实现结果(给了文档里两个示例的运行结果)1.当输入数据值“abc”时候的实验结果:2.当输入数据值为...
  • python SM3密码杂凑算法

    千次阅读 2021-02-01 18:08:35
        本文本规定了SM3密码杂凑算法的计算方法和计算步骤,并给出了运算示例。     本文本适用于商用密码应用中的数字签名和验证、消息认证码的生成与验证以及随机数的生成,可满足多种密码应用的安全需求。...
  • 代码中实现了电码本ECB模式和密文分组连接CBC模式,SM3.java和SM4.java为算法实现类,utils的都是根据实现类写的工具,可以根据需要调用杂凑算法SM3的杂凑功能获得杂凑值。 SM4.java中 sm4_crypt_ecb(SM4_...
  • SM3主要用数字签名及验证、消息认证码生成及验证、随机数生成等,其安全性及效率与SHA-256相当。可以用MD5作为对比理解。校验结果为256位,该算法已公开。 SM4.0(原名SMS4.0)是中华人民共和国政府采用的一种分组...
  • 关于国密算法 SM1,SM2,SM3,SM4 的笔记 国密即国家密码局认定的国产密码算法。主要有SM1,SM2,SM3,SM4。密钥长度和分组长度均为128位。 SM1 为对称加密。其加密强度与AES相当。该算法不公开,调用该算法时,需要...
  • 主要有SM1,SM2,SM3,SM4。密钥长度和分组长度均为128位。 SM1为对称加密。其加密强度与AES相当。该算法不公开,调用该算法时,需要通过加密芯片的接口进行调用。 SM2为非对称加密,基于ECC。该算法已公开。由于...
  • SM1对称密码SM1 算法是分组密码算法,分组长度为128位,密钥长度都为 128 比特,算法安全保密强度及相关软硬件实现性能与 AES 相当,算法不公开,仅以IP核的形式存在于芯片中。采用该算法已经研制了系列芯片、智能IC...
  • GMSSL 支持SM2/SM3/SM4

    2021-09-27 17:31:57
    GmSSL是一个开源的加密包的python实现,支持SM2/SM3/SM4等国密(国家商用密码)算法、项目采用对商业应用友好的类BSD开源许可证,开源且可以用于闭源的商业应用。 SM2算法 安装 pip install gmssl RSA算法的危机在于其...
  • (2)创建用户 如下示例中,创建了test用户,通过系统表pg_authid的rolpassword字段可以查看用户创建时对应的加密方式,图示即对应SM3加密 (3)在pg_hba.conf文件中配置认证方式为SM3 此时test用户远程登录方可...
  • SM1,SM2,SM3,SM4刨析

    千次阅读 2020-12-24 05:28:03
    主要有SM1,SM2,SM3,SM4。密钥长度和分组长度均为128位。SM1为对称加密。其加密强度与AES相当。该算法不公开,调用该算法时,需要通过加密芯片的接口进行调用。SM2为非对称加密,基于ECC。该算法已公开。由于该...
  • springboot 和 js (vue) 实现SM3加密 防篡改 一、以下是对引入SM3进行说明 1.首先导入jar <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</...
  • 【转】C#实现SM3国密加密

    千次阅读 2021-01-07 13:15:21
    C#实现SM3国密加密 本文主要讲解“国密加密算法”SM系列之SM3的C#实现方法,加密规则请详阅国密局发布的文档。 首先需第三方Nuget包:Portable.BouncyCastle(源码来自http://www.bouncycastle.org/csharp/) 1.1...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 206,678
精华内容 82,671
关键字:

sm3