Пример #1
0
        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);

            SM2Cipher cipher = new SM2Cipher();
            var       sm2    = SM2CryptoServiceProvider.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));

            String sc1 = c1.GetEncoded().byteToHex();
            String sc2 = source.byteToHex();
            String sc3 = c3.byteToHex();

            return((sc1 + sc2 + sc3).ToUpper());
        }
Пример #2
0
        public static byte[] Decrypt(byte[] privateKey, byte[] encryptedData)
        {
            if (null == privateKey || privateKey.Length == 0)
            {
                return(null);
            }
            if (encryptedData == null || encryptedData.Length == 0)
            {
                return(null);
            }
            //加密字节数组转换为十六进制的字符串 长度变为encryptedData.length * 2
            var data = encryptedData.byteToHex();// Encoding.UTF8.GetString(Hex.Encode(encryptedData));

            byte[] c1Bytes = data.Substring(0, 130).hexToByte();
            int    c2Len   = encryptedData.Length - 97;

            byte[] c2 = data.Substring(130, 2 * c2Len).hexToByte();
            byte[] c3 = data.Substring(130 + 2 * c2Len, 64).hexToByte();

            //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)));

            SM2CryptoServiceProvider sm2 = SM2CryptoServiceProvider.Instance;
            BigInteger userD             = new BigInteger(1, privateKey);

            ECPoint   c1     = sm2.ecc_curve.DecodePoint(c1Bytes);
            SM2Cipher cipher = new SM2Cipher();

            cipher.Init_dec(userD, c1);
            cipher.Decrypt(c2);
            cipher.Dofinal(c3);

            return(c2);
        }