首页 > 其他分享 >RSA加密解密

RSA加密解密

时间:2024-03-22 11:33:05浏览次数:23  
标签:加密 string RSA 解密 key elems new byte binr

c# 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class RSA
    {
        /// <summary>
        /// RSA公钥加密
        /// </summary>
        /// <param name="publickey">公钥</param>
        /// <param name="content">待加密字符串</param>
        /// <param name="input_charset">编码格式,UTF-8</param>
        /// <returns></returns>
        public static string RasEncrypt(string publickey, string content, string input_charset)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.ImportParameters(ConvertFromPublicKey(publickey));
            cipherbytes = rsa.Encrypt(Encoding.GetEncoding(input_charset).GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes);
        }

        /// <summary>
        /// RSA私钥解密
        /// </summary>
        /// <param name="resData">RSA加密后字符串</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="input_charset">编码格式,UTF-8</param>
        /// <returns>明文</returns>
        public static string RsaDecrypt(string resData, string privateKey, string input_charset)
        {
            byte[] DataToDecrypt = Convert.FromBase64String(resData);
            string result = "";
            for (int j = 0; j < DataToDecrypt.Length / 128; j++)
            {
                byte[] buf = new byte[128];
                for (int i = 0; i < 128; i++)
                {

                    buf[i] = DataToDecrypt[i + 128 * j];
                }
                result += decrypt(buf, privateKey, input_charset);
            }
            return result;
        }

        #region 内部方法

        private static string decrypt(byte[] data, string privateKey, string input_charset)
        {
            string result = "";
            RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
            using (var sh = SHA1.Create())
            {
                byte[] source = rsa.Decrypt(data, false);
                char[] asciiChars = new char[Encoding.GetEncoding(input_charset).GetCharCount(source, 0, source.Length)];
                Encoding.GetEncoding(input_charset).GetChars(source, 0, source.Length, asciiChars, 0);
                result = new string(asciiChars);
                return result;
            }

        }

        private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
        {
            RSACryptoServiceProvider rsa = DecodeRSAPrivateKey(Convert.FromBase64String(pemstr));
            return rsa;
        }

        private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

            // --------- Set up stream to decode the asn.1 encoded RSA private key ------
            MemoryStream mem = new MemoryStream(privkey);
            BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            byte bt = 0;
            ushort twobytes = 0;
            int elems = 0;
            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte(); //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16(); //advance 2 bytes
                else
                    return null;

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                    return null;
                bt = binr.ReadByte();
                if (bt != 0x00)
                    return null;


                //------ all private key components are Integer sequences ----
                elems = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ = binr.ReadBytes(elems);


                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                CspParameters CspParameters = new CspParameters();
                CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(1024, CspParameters);
                RSAParameters RSAparams = new RSAParameters();
                RSAparams.Modulus = MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D = D;
                RSAparams.P = P;
                RSAparams.Q = Q;
                RSAparams.DP = DP;
                RSAparams.DQ = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return RSA;
            }
            catch
            {
                return null;
            }
            finally
            {
                binr.Dispose();
            }
        }

        private static int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02) //expect integer
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte(); // data size in next byte
            else
                if (bt == 0x82)
            {
                highbyte = binr.ReadByte(); // data size in next 2 bytes
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt; // we already have the data size
            }

            while (binr.ReadByte() == 0x00)
            { //remove high order zeros in data
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
            return count;
        }

        #endregion

        #region 生成的Pem
        private static RSAParameters ConvertFromPublicKey(string pemFileConent)
        {

            if (string.IsNullOrEmpty(pemFileConent))
            {
                throw new ArgumentNullException("pemFileConent", "This arg cann't be empty.");
            }
            pemFileConent = pemFileConent.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\n", "").Replace("\r", "");
            byte[] keyData = Convert.FromBase64String(pemFileConent);
            bool keySize1024 = (keyData.Length == 162);
            bool keySize2048 = (keyData.Length == 294);
            if (!(keySize1024 || keySize2048))
            {
                throw new ArgumentException("pem file content is incorrect, Only support the key size is 1024 or 2048");
            }
            byte[] pemModulus = (keySize1024 ? new byte[128] : new byte[256]);
            byte[] pemPublicExponent = new byte[3];
            Array.Copy(keyData, (keySize1024 ? 29 : 33), pemModulus, 0, (keySize1024 ? 128 : 256));
            Array.Copy(keyData, (keySize1024 ? 159 : 291), pemPublicExponent, 0, 3);
            RSAParameters para = new RSAParameters();
            para.Modulus = pemModulus;
            para.Exponent = pemPublicExponent;
            return para;
        }

        #endregion

    }
}

对应python版本:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64

# 生成 RSA 密钥对
key = RSA.generate(2048)

# 获取公钥和私钥
public_key = key.publickey().export_key()
private_key = key.export_key()


print("Public key:", public_key.decode())
print("Private key:", private_key.decode())

# 加密函数
def rsa_encrypt(message, public_key):
    rsa_key = RSA.import_key(public_key)
    cipher = PKCS1_v1_5.new(rsa_key)
    encrypted_message = cipher.encrypt(message.encode())
    return base64.b64encode(encrypted_message)

# 解密函数
def rsa_decrypt(ciphertext, private_key):
    rsa_key = RSA.import_key(private_key)
    cipher = PKCS1_v1_5.new(rsa_key)
    decrypted_message = cipher.decrypt(base64.b64decode(ciphertext), None)
    return decrypted_message.decode()

# 要加密的消息
message = "Hello, this is a secret message!"

# 使用公钥加密消息
encrypted_message = rsa_encrypt(message, public_key)
print("Encrypted message:", encrypted_message)

# 使用私钥解密消息
decrypted_message = rsa_decrypt(encrypted_message, private_key)
print("Decrypted message:", decrypted_message)

 

标签:加密,string,RSA,解密,key,elems,new,byte,binr
From: https://www.cnblogs.com/onlyou13/p/18089103

相关文章

  • DES加密
    DES加密一.DES加密流程​​1.初始置换根据初始置换表,对输入的64位的明文按照比特位数进行替换。即加密和解密的时候应该是一张8*8的表来进行替换。2.f运算f运算的参数为每一轮的密钥k和上一轮的R。​​对于32位的输入数据首先经过拓展变换得到48位的数据,然后与48位的......
  • RC4加密
    RC4加密一.介绍在密码学中,RC4(来自RivestCipher4的缩写)是一种流加密算法(基于bit进行加密),密钥长度可变。它加解密使用相同的密钥,因此也属于对称加密算法。所谓对称加密,就是加密和解密的过程是一样的。RC4是有线等效加密(WEP)中采用的加密算法,也曾经是TLS可采用的算法之一。RC4......
  • AES加密
    AES加密一.加密流程​​AES未使用Feistel结构。其前N-1轮由4个不同的变换组成:字节代替、行移位、列混淆和轮密钥加。最后一轮仅包含三个变换。而在第一轮前面有一个起始的单变换(轮密钥加),可以视为0轮。字节代替(SubBytes):用一个S盒完成分组的字节到字节的代替。行移位(ShiftRows):......
  • AES加密
    AES算法加密(ECB模式),加密后进行base64编码异常Specifiedkeyisnotavalidsizeforthisalgorithm解决方法:AES加密中参数key应是32位,如果位数不对会报此错。///<summary>///AES算法加密(ECB模式)将明文加密,加密后进行base64编码,返回密文///</summary>///<p......
  • vite+vue3+vuex 加密
    1.安装JSEncrypt  npminstalljsencrypt2.加密方法//加密算法import{JSEncrypt}from'jsencrypt';//加密functionencryptText(text){ constpublicKey='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCh5Nk2GLiyQFMIU+h3OEA4UeFbu3dCH5sjd/sLTxxvwjXq7JLqJbt2rC......
  • C++模板实现之谜:为何只能在头文件中?解密原因与高级分离技术
     概述:C++中模板必须在头文件中实现,因为编译器需要可见的实现以生成模板具体实例的代码。通过头文件,确保模板在每个编译单元中都能被正确展开,提高可维护性。在C++中,模板只能在头文件中实现的主要原因是编译器在使用模板时需要生成对应的代码,而这部分代码必须在编译时可见。以......
  • TimesURL: 用于通用时间序列表征学习的自监督对比学习《TimesURL: Self-supervised Co
    2024年3月18日,最近有点忙,但是这周四周五都要汇报,不想往后推了,早汇报完早结束,硬着头皮先看这一篇,这篇年前就说要看,还保存了书签,但是一直没看,今天趁着中午的时间看一下。(现在14:01,开始看,我的草稿箱里躺着的18篇草稿,Sorry,以后有空再填坑.)论文:TimesURL:Self-supervisedContrasti......
  • 提升Java编程安全性-代码加密混淆工具的重要性和应用
     在Java编程领域中,保护代码安全性和知识产权至关重要。本文旨在探讨代码加密混淆工具在提升代码安全性和保护知识产权方面的重要性。我们将介绍几款流行的Java代码加密混淆工具,如ProGuard、DexGuard、Jscrambler、DashO和ipaguard,并分析它们的功能和适用场景,旨在帮助开发者选择......
  • 密码加密|jsencrypt|md5|加密解密的两种方式
    一、md5npminstallmd5二、JSEncrypt2.1介绍JSEncrypt属于RSA加密,RSA加密算法是一种非对称加密算法;2.2使用安装:npminstalljsencrypt--dev封装工具:utils/jsencrypt.jsimportJSEncryptfrom'jsencrypt/bin/jsencrypt.min'//密钥对生成http://web.cha......
  • RSA算法揭秘:加密世界的守护者
    RSA算法起源:RSA算法是由RonRivest、AdiShamir和LeonardAdleman在1977年共同提出的。它是一种非对称加密算法,基于两个大素数的乘积难以分解的数论问题。RSA算法包括公钥和私钥,用于加密和解密数据,实现了安全的通信和数据传输。首页|一个覆盖广泛主题工具的高效在线平台(a......