• 整理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];
            }
        }
    

      

  • 相关阅读:
    C语言I博客作业08
    博客作业6
    C语言I博客作业05
    C语言I博客作业03
    5.C#2.0之不完整类型(完成)
    4.C#2.0之迭代器(完成)
    3.C#2.0之匿名方法(完成)
    2.C#2.0之泛型(完成)
    1.C#2.0之2.0简介(完成)
    18.C#基础之不安全代码(完成)
  • 原文地址:https://www.cnblogs.com/yzpopulation/p/12870536.html
Copyright © 2020-2023  润新知