예제 #1
0
        /// <summary>
        /// Decrypt by private key
        /// </summary>
        /// <param name="dataBytes"></param>
        /// <param name="privateKey"></param>
        /// <param name="encoding"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static byte[] DecryptByPrivateKeyAsBytes(byte[] dataBytes, string privateKey, Encoding encoding = default, SM2Mode mode = SM2Mode.C1C3C2)
        {
            if (privateKey is null || privateKey.Length == 0)
            {
                return(null);
            }

            if (dataBytes is null || dataBytes.Length == 0)
            {
                return(null);
            }

            // ReSharper disable once ExpressionIsAlwaysNull
            encoding ??= encoding.SafeValue();

            var privateKeyBytes = Hex.Decode(encoding.GetBytes(privateKey));

            var(c1, c2, c3) = GetContent(dataBytes, mode, encoding);

            var sm2   = SM2Core.Instance;
            var userD = new BigInteger(1, privateKeyBytes);

            var c      = sm2.ecc_curve.DecodePoint(c1);
            var cipher = new SM2Core.Cipher();

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

            return(c2);
        }
예제 #2
0
        /// <summary>
        /// Encrypt by public key
        /// </summary>
        /// <param name="dataBytes"></param>
        /// <param name="publicKey"></param>
        /// <param name="encoding"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static string EncryptByPublicKey(byte[] dataBytes, string publicKey, Encoding encoding = default, SM2Mode mode = SM2Mode.C1C3C2)
        {
            if (publicKey is null || publicKey.Length == 0)
            {
                return(null);
            }

            if (dataBytes is null || dataBytes.Length == 0)
            {
                return(null);
            }

            // ReSharper disable once ExpressionIsAlwaysNull
            encoding ??= encoding.SafeValue();

            var publicKeyBytes = Hex.Decode(encoding.GetBytes(publicKey));

            var source = new byte[dataBytes.Length];

            Array.Copy(dataBytes, 0, source, 0, dataBytes.Length);

            var cipher = new SM2Core.Cipher();
            var sm2    = SM2Core.Instance;

            var userKey = sm2.ecc_curve.DecodePoint(publicKeyBytes);

            var c1 = cipher.Init_enc(sm2, userKey);

            cipher.Encrypt(source);

            var c3 = new byte[32];

            cipher.Dofinal(c3);

            var c1Str = encoding.GetString(Hex.Encode(c1.GetEncoded()));
            var c2Str = encoding.GetString(Hex.Encode(source));
            var c3Str = encoding.GetString(Hex.Encode(c3));

            return(mode == SM2Mode.C1C2C3
                ? (c1Str + c2Str + c3Str).ToUpper()
                : (c1Str + c3Str + c2Str).ToUpper());
        }