zoukankan      html  css  js  c++  java
  • 整理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];
            }
        }
    

      

  • 相关阅读:
    计算机中的进制和编码
    操作系统简史
    电脑结构和CPU、内存、硬盘三者之间的关系
    电脑简史
    使用开源my-deploy工具实现开发环境的代码自动化部署
    使用Let’s Encrypt创建nginx免费SSL证书
    VM ESXI 服务器虚拟化资料积累
    python mysql连接函数
    python日期格式转换小记
    Python模块学习
  • 原文地址:https://www.cnblogs.com/yzpopulation/p/12870536.html
Copyright © 2011-2022 走看看