zoukankan      html  css  js  c++  java
  • RSA加密与解密

    /// <summary>
    /// RSA 公钥加密
    /// </summary>
    /// <param name="content">要加密的内容</param>
    /// <param name="publickey">公钥</param>
    /// <returns></returns>
    public static string EncryptByPublicKey(string content, string publickey)
    {
    byte[] s = Convert.FromBase64String(publickey);
    AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(s);
    IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
    //公钥加密
    c.Init(true, publicKey);
    byte[] byteData = Encoding.UTF8.GetBytes(content);
    byteData = c.DoFinal(byteData, 0, byteData.Length);

    return Convert.ToBase64String(byteData);
    }

    /// <summary>
    /// RSA加密
    /// </summary>
    /// <param name="content">加密明文</param>
    /// <param name="privatekey">私钥</param>
    /// <returns>返回密文</returns>
    public static string RSAEncry(string content, string privatekey)
    {
    AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(privatekey));
    IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
    //私钥加密
    c.Init(true, privateKey);
    byte[] byteData = Encoding.UTF8.GetBytes(content);
    byteData = c.DoFinal(byteData, 0, byteData.Length);
    return Convert.ToBase64String(byteData);
    }

    /// <summary>
    /// RSA解密
    /// </summary>
    /// <param name="content">密文</param>
    /// <param name="privatekey">私钥</param>
    /// <returns>明文</returns>
    public static string RSADeEncry(string content, string privatekey)
    {
    try
    {
    MemoryStream bufferStream = new MemoryStream();
    byte[] bytData = Convert.FromBase64String(content);
    int inputLength = bytData.Length;

    AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(privatekey));
    IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
    cipher.Init(false, privateKey);
    int offSet = 0;
    byte[] cache;
    int i = 0;
    while (inputLength - offSet > 0)
    {
    if (inputLength - offSet > 128)
    {
    cache = cipher.DoFinal(bytData, offSet, 128);
    }
    else
    {
    cache = cipher.DoFinal(bytData, offSet, inputLength - offSet);
    }
    bufferStream.Write(cache, 0, cache.Length);
    i++;
    offSet = i * 128;
    }
    byte[] decryptedData = bufferStream.ToArray();
    bufferStream.Close();
    return Encoding.UTF8.GetString(bufferStream.ToArray());
    }
    catch (Exception e)
    {
    return e.Message;
    }
    }

  • 相关阅读:
    高德地图API之公交路线
    高德地图API之骑行路线
    高德地图API之货车路线
    高德地图API之步行路线
    高德地图API之驾车路线
    高德地图API常用控件的添加与删除(鹰眼、工具条、比例尺)
    高德地图API,地图类型切换(卫星地图)
    高德地图API之缩放比例尺控件+3D转换
    Laravel 虚拟开发环境 Homestead 密码
    优化mysql
  • 原文地址:https://www.cnblogs.com/brucehome/p/6517771.html
Copyright © 2011-2022 走看看