• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
梦幻仙境的精灵
博客园    首页    新随笔    联系   管理    订阅  订阅

RSA 加解密

        #region RSA
        public static byte[] GetBytes(String num)
        {
            BigInteger n = new BigInteger(num, 10);
            String s = n.ToString(2);
            if (s.Length % 8 > 0)
            {
                s = new String('0', 8 - s.Length % 8) + s;
            }
            byte[] data = new byte[s.Length / 8];
            String ocetstr;
            for (int i = 0; i < data.Length; i++)
            {
                ocetstr = s.Substring(8 * i, 8);
                data[i] = Convert.ToByte(ocetstr, 2);
            }
            return data;
        }

        /// <summary> 
        /// 字节数组转16进制字符串 
        /// </summary> 
        /// <param name="bytes"></param> 
        /// <returns></returns> 
        public static String ConvByteArrayToHex(byte[] data)
        {
            String s = "";
            for (int i = 0; i < data.Length; i++)
            {
                s += Convert.ToString(data[i], 16);
            }
            return s.ToUpper();
        }
        public static string RSAEncrypt(string Modulus, string Exponent, string content)
        {
            var param = new RSAParameters();
            param.Exponent = GetBytes(Exponent);
            param.Modulus = GetBytes(Modulus);
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(param);

            int CellLength = new BigInteger(param.Modulus).bitCount() / 8;

            byte[] bInput = Encoding.UTF8.GetBytes(content);


            int MaxLength = CellLength - 11;
            int GroupLength = (int)Math.Ceiling(bInput.Length * 1.00 / MaxLength);

            byte[] cipherText = new byte[GroupLength * CellLength];
            for (int i = 0; i < GroupLength; i++)
            {
                int len = MaxLength < bInput.Length - MaxLength * i ? MaxLength
                        : bInput.Length - MaxLength * i;
                byte[] inByte = new byte[len];
                Buffer.BlockCopy(bInput, MaxLength * i, inByte, 0, len);

                byte[] temp = rsa.Encrypt(inByte, false);
                Buffer.BlockCopy(temp, 0, cipherText, i * CellLength, CellLength);
            }
            //cipherText = rsa.Encrypt(bInput, false);
            //return Convert.ToBase64String(cipherText);
            //return toHex(cipherText);
            return BitConverter.ToString(cipherText).Replace("-", "");

        }


        #endregion

 

posted @ 2014-12-19 10:17  梦幻仙境的精灵  阅读(168)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3