整理SM4国密算法

         public class Sm4Encryptor
    {
        public byte[] KeyBytes = new byte[16];

        private Sm4Encryptor()
        {
            cipher = new PaddedBufferedBlockCipher(new SM4Engine());
        }

        private PaddedBufferedBlockCipher cipher { get; }
        private static Sm4Encryptor UniqueInstance { get; set; }

        public static byte[] GenerateArray(int length)
        {
            var rnd = new SecureRandom();
            var output = new byte[length];
            for (var i = 0; i < length; i++) output[i] = (byte) (rnd.Next() % 256);
            return output;
        }

        public static Sm4Encryptor GetInstance()
        {
            return UniqueInstance ??= new Sm4Encryptor();
        }

        public void SetKey(byte[] bytes)
        {
            if (bytes.Length > 16) throw new Exception("Key Size Must 128 bit (16 bytes)");
            Array.Copy(bytes, KeyBytes, bytes.Length);
        }

        public void SetKey(string key)
        {
            SetKey(Encoding.UTF8.GetBytes(key));
        }

        public byte[] DoEncrypt(byte[] plainBytes, byte[] keyBytes = null)
        {
            keyBytes ??= KeyBytes;
            cipher.Init(true, new KeyParameter(keyBytes));
            var e = new byte[cipher.GetOutputSize(plainBytes.Length)];
            var e1 = cipher.ProcessBytes(plainBytes, e, 0);
            var e2 = cipher.DoFinal(e, e1);
            return e;
        }

        public byte[] DoDecrypt(byte[] encryptBytes, byte[] keyBytes = null)
        {
            keyBytes ??= KeyBytes;
            cipher.Init(false, new KeyParameter(keyBytes));
            var e = new byte[cipher.GetOutputSize(encryptBytes.Length)];
            var e1 = cipher.ProcessBytes(encryptBytes, e, 0);
            var e2 = cipher.DoFinal(e, e1);
            var e3 = e1 + e2;
            return e[..e3];
        }
    }

  

posted @ 2020-05-11 17:38  月渊  阅读(3681)  评论(0编辑  收藏  举报