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];
            }
        }
    

      

  • 相关阅读:
    08Alpha版(内部测试版)发布
    意见汇总
    第一阶段SCRUM
    团队总结
    与学习通app对比分析
    团队第一阶段评价
    第一阶段完成情况说明
    效绩评估 第二阶段
    效绩评估 第一阶段
    软件对比
  • 原文地址:https://www.cnblogs.com/yzpopulation/p/12870536.html
Copyright © 2011-2022 走看看