RSA算法实现(C++)

fenggy0248 2013-04-27 08:41:56
如题,要求实现2048位以上的
求源码
...全文
2857 23 打赏 收藏 转发到动态 举报
写回复
用AI写文章
23 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuanhong2910 2013-04-29
  • 打赏
  • 举报
回复
http://www.cryptopp.com/
yuanhong2910 2013-04-29
  • 打赏
  • 举报
回复
我勒个去,botan, crypto++, 这些库都是开源的,下载下来后把需要的地方扣出来编译一下就搞定了,什么随机数生成,大整数都实现好了。
赵4老师 2013-04-28
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;
inline int compare(string str1,string str2) {//相等返回0,大于返回1,小于返回-1
         if (str1.size()>str2.size()) return 1; //长度长的整数大于长度小的整数
    else if (str1.size()<str2.size()) return -1;
    else                              return str1.compare(str2); //若长度相等,则头到尾按位比较
}
string SUB_INT(string str1,string str2);
string ADD_INT(string str1,string str2) {//高精度加法
    int sign=1; //sign 为符号位
    string str;
    if (str1[0]=='-') {
        if (str2[0]=='-') {
            sign=-1;
            str=ADD_INT(str1.erase(0,1),str2.erase(0,1));
        } else {
            str=SUB_INT(str2,str1.erase(0,1));
        }
    } else {
        if (str2[0]=='-') {
            str=SUB_INT(str1,str2.erase(0,1));
        } else { //把两个整数对齐,短整数前面加0补齐
            string::size_type L1,L2;
            int i;
            L1=str1.size();
            L2=str2.size();
            if (L1<L2) {
                for (i=1;i<=L2-L1;i++) str1="0"+str1;
            } else {
                for (i=1;i<=L1-L2;i++) str2="0"+str2;
            }
            int int1=0,int2=0; //int2 记录进位
            for (i=str1.size()-1;i>=0;i--) {
                int1=(int(str1[i])-'0'+int(str2[i])-'0'+int2)%10;
                int2=(int(str1[i])-'0'+int(str2[i])-'0'+int2)/10;
                str=char(int1+'0')+str;
            }
            if (int2!=0) str=char(int2+'0')+str;
        }
    }
    //运算后处理符号位
    if ((sign==-1)&&(str[0]!='0')) str="-"+str;
    return str;
}
string SUB_INT(string str1,string str2) {//高精度减法
    int sign=1; //sign 为符号位
    string str;
    int i,j;
    if (str2[0]=='-') {
        str=ADD_INT(str1,str2.erase(0,1));
    } else {
        int res=compare(str1,str2);
        if (res==0) return "0";
        if (res<0) {
            sign=-1;
            string temp =str1;
            str1=str2;
            str2=temp;
        }
        string::size_type tempint;
        tempint=str1.size()-str2.size();
        for (i=str2.size()-1;i>=0;i--) {
            if (str1[i+tempint]<str2[i]) {
                j=1;
                while (1) {//zhao4zhong1添加
                    if (str1[i+tempint-j]=='0') {
                        str1[i+tempint-j]='9';
                        j++;
                    } else {
                        str1[i+tempint-j]=char(int(str1[i+tempint-j])-1);
                        break;
                    }
                }
                str=char(str1[i+tempint]-str2[i]+':')+str;
            } else {
                str=char(str1[i+tempint]-str2[i]+'0')+str;
            }
        }
        for (i=tempint-1;i>=0;i--) str=str1[i]+str;
    }
    //去除结果中多余的前导0
    str.erase(0,str.find_first_not_of('0'));
    if (str.empty()) str="0";
    if ((sign==-1) && (str[0]!='0')) str ="-"+str;
    return str;
}
string MUL_INT(string str1,string str2) {//高精度乘法
    int sign=1; //sign 为符号位
    string str;
    if (str1[0]=='-') {
        sign*=-1;
        str1 =str1.erase(0,1);
    }
    if (str2[0]=='-') {
        sign*=-1;
        str2 =str2.erase(0,1);
    }
    int i,j;
    string::size_type L1,L2;
    L1=str1.size();
    L2=str2.size();
    for (i=L2-1;i>=0;i--) { //模拟手工乘法竖式
        string tempstr;
        int int1=0,int2=0,int3=int(str2[i])-'0';
        if (int3!=0) {
            for (j=1;j<=(int)(L2-1-i);j++) tempstr="0"+tempstr;
            for (j=L1-1;j>=0;j--) {
                int1=(int3*(int(str1[j])-'0')+int2)%10;
                int2=(int3*(int(str1[j])-'0')+int2)/10;
                tempstr=char(int1+'0')+tempstr;
            }
            if (int2!=0) tempstr=char(int2+'0')+tempstr;
        }
        str=ADD_INT(str,tempstr);
    }
    //去除结果中的前导0
    str.erase(0,str.find_first_not_of('0'));
    if (str.empty()) str="0";
    if ((sign==-1) && (str[0]!='0')) str="-"+str;
    return str;
}
string DIVIDE_INT(string str1,string str2,int flag) {//高精度除法。flag==1时,返回商; flag==0时,返回余数
    string quotient,residue; //定义商和余数
    int sign1=1,sign2=1;
    if (str2 == "0") {  //判断除数是否为0
        quotient= "ERROR!";
        residue = "ERROR!";
        if (flag==1) return quotient;
        else         return residue ;
    }
    if (str1=="0") { //判断被除数是否为0
        quotient="0";
        residue ="0";
    }
    if (str1[0]=='-') {
        str1   = str1.erase(0,1);
        sign1 *= -1;
        sign2  = -1;
    }
    if (str2[0]=='-') {
        str2   = str2.erase(0,1);
        sign1 *= -1;
    }
    int res=compare(str1,str2);
    if (res<0) {
        quotient="0";
        residue =str1;
    } else if (res == 0) {
        quotient="1";
        residue ="0";
    } else {
        string::size_type L1,L2;
        L1=str1.size();
        L2=str2.size();
        string tempstr;
        tempstr.append(str1,0,L2-1);
        for (int i=L2-1;i<L1;i++) { //模拟手工除法竖式
            tempstr=tempstr+str1[i];
            tempstr.erase(0,tempstr.find_first_not_of('0'));//zhao4zhong1添加
            if (tempstr.empty()) tempstr="0";//zhao4zhong1添加
            for (char ch='9';ch>='0';ch--) { //试商
                string str;
                str=str+ch;
                if (compare(MUL_INT(str2,str),tempstr)<=0) {
                    quotient=quotient+ch;
                    tempstr =SUB_INT(tempstr,MUL_INT(str2,str));
                    break;
                }
            }
        }
        residue=tempstr;
    }
    //去除结果中的前导0
    quotient.erase(0,quotient.find_first_not_of('0'));
    if (quotient.empty()) quotient="0";
    if ((sign1==-1)&&(quotient[0]!='0')) quotient="-"+quotient;
    if ((sign2==-1)&&(residue [0]!='0')) residue ="-"+residue ;
    if (flag==1) return quotient;
    else         return residue ;
}
string DIV_INT(string str1,string str2) {//高精度除法,返回商
    return DIVIDE_INT(str1,str2,1);
}
string MOD_INT(string str1,string str2) {//高精度除法,返回余数
    return DIVIDE_INT(str1,str2,0);
}
int main() {
    char ch;
    string s1,s2,res;

    while (cin>>s1>>ch>>s2) {
        switch (ch) {
            case '+':res=ADD_INT(s1,s2);break;
            case '-':res=SUB_INT(s1,s2);break;
            case '*':res=MUL_INT(s1,s2);break;
            case '/':res=DIV_INT(s1,s2);break;
            case '%':res=MOD_INT(s1,s2);break;
            default :                   break;
        }
        cout<<res<<endl;
    }
    return(0);
}
fenggy0248 2013-04-28
  • 打赏
  • 举报
回复
引用 15 楼 zhao4zhong1 的回复:
using  System;
using  System.Security.Cryptography;
using  System.IO;
using  System.Text;

private	 byte[]	 Keys  =  {	 0xEF,	0xAB,  0x56,  0x78,	 0x90,	0x34,  0xCD,  0x12	};//默认密钥向量
///	 <summary>
///	 DES加密字符串
///	 </summary>
///	 <param	 name="encryptString">待加密的字符串</param>
///	 <param	 name="encryptKey">加密密钥,要求为8位</param>
///	 <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public	string	EncryptDES(string  encryptString,  string  encryptKey)
{
		try
		{
				byte[]	rgbKey	=  Encoding.UTF8.GetBytes(encryptKey.Substring(0,  8));
				byte[]	rgbIV  =  Keys;
				byte[]	inputByteArray	=  Encoding.UTF8.GetBytes(encryptString);
				DESCryptoServiceProvider  dCSP	=  new	DESCryptoServiceProvider();
				MemoryStream  mStream  =  new  MemoryStream();
				CryptoStream  cStream  =  new  CryptoStream(mStream,  dCSP.CreateEncryptor(rgbKey,	rgbIV),	 CryptoStreamMode.Write);
				cStream.Write(inputByteArray,  0,  inputByteArray.Length);
				cStream.FlushFinalBlock();
				return	Convert.ToBase64String(mStream.ToArray());
		}
		catch
		{
				return	encryptString;
		}
}

///	 <summary>
///	 DES解密字符串
///	 </summary>
///	 <param	 name="decryptString">待解密的字符串</param>
///	 <param	 name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
///	 <returns>解密成功返回解密后的字符串,失败返源串</returns>
public	string	DecryptDES(string  decryptString,  string  decryptKey)
{
		try
		{
				byte[]	rgbKey	=  Encoding.UTF8.GetBytes(decryptKey.Substring(0,  8));
				byte[]	rgbIV  =  Keys;
				byte[]	inputByteArray	=  Convert.FromBase64String(decryptString);
				DESCryptoServiceProvider  DCSP	=  new	DESCryptoServiceProvider();
				MemoryStream  mStream  =  new  MemoryStream();
				CryptoStream  cStream  =  new  CryptoStream(mStream,  DCSP.CreateDecryptor(rgbKey,	rgbIV),	 CryptoStreamMode.Write);
				cStream.Write(inputByteArray,  0,  inputByteArray.Length);
				cStream.FlushFinalBlock();
				return	Encoding.UTF8.GetString(mStream.ToArray());
		}
		catch
		{
				return	decryptString;
		}
}
///	 <summary>
///	 use  sha1	to	encrypt	 string
///	 </summary>
public	string	SHA1_Encrypt(string	 Source_String)
{
		byte[]	StrRes	=  Encoding.Default.GetBytes(Source_String);
		HashAlgorithm  iSHA	 =	new	 SHA1CryptoServiceProvider();
		StrRes	=  iSHA.ComputeHash(StrRes);
		StringBuilder  EnText  =  new  StringBuilder();
		foreach	 (byte	iByte  in  StrRes)
		{
				EnText.AppendFormat("{0:x2}",  iByte);
		}
		return	EnText.ToString();
}

namespace  Microsoft.Samples.Security.PublicKey
{
	class  App
	{
		//	Main  entry	 point
		static	void  Main(string[]	 args)
		{
			//	Instantiate	 3	People	for	 example.  See	the	 Person	 class	below
			Person	alice  =  new  Person("Alice");
			Person	bob	 =	new	 Person("Bob");
			Person	steve  =  new  Person("Steve");

			//	Messages  that	will  exchanged.  See  CipherMessage  class	 below
			CipherMessage  aliceMessage;
			CipherMessage  bobMessage;
			CipherMessage  steveMessage;

			//	Example	 of	 encrypting/decrypting	your  own  message
			Console.WriteLine("Encrypting/Decrypting  Your  Own  Message");
			Console.WriteLine("-----------------------------------------");

			//	Alice  encrypts	 a	message	 using	her	 own  public  key
			aliceMessage  =	 alice.EncryptMessage("Alice  wrote  this  message");
			//	then  using	 her  private  key	can	 decrypt  the  message
			alice.DecryptMessage(aliceMessage);
			//	Example	 of	 Exchanging	 Keys  and	Messages
			Console.WriteLine();
			Console.WriteLine("Exchanging  Keys  and  Messages");
			Console.WriteLine("-----------------------------------------");

			//	Alice  Sends  a	 copy  of  her	public	key	 to	 Bob  and  Steve
			bob.GetPublicKey(alice);
			steve.GetPublicKey(alice);

			//	Bob	 and  Steve	 both  encrypt	messages  to  send	to	Alice
			bobMessage	=  bob.EncryptMessage("Hi  Alice!  -  Bob.");
			steveMessage  =	 steve.EncryptMessage("How  are  you?  -  Steve");

			//	Alice  can	decrypt	 and  read	both  messages
			alice.DecryptMessage(bobMessage);
			alice.DecryptMessage(steveMessage);

			Console.WriteLine();
			Console.WriteLine("Private  Key  required  to  read  the  messages");
			Console.WriteLine("-----------------------------------------");

			//	Steve  cannot  read	 the  message  that	 Bob  encrypted
			steve.DecryptMessage(bobMessage);
			//	Not	 even  Bob	can	 use  the  Message	he	encrypted  for	Alice.
			//	The	 RSA  private  key	is	required  to  decrypt  the	RS2	 key  used
			//	in	the	 decryption.
			bob.DecryptMessage(bobMessage);

		}  //  method  Main
	}  //  class  App

	class  CipherMessage
	{
		public	byte[]	cipherBytes;	//	RC2	 encrypted	message	 text
		public	byte[]	rc2Key;				 //	 RSA  encrypted	 rc2  key
		public	byte[]	rc2IV;				  //  RC2  initialization  vector
	}

	class  Person
	{
		private	 RSACryptoServiceProvider  rsa;
		private	 RC2CryptoServiceProvider  rc2;
		private	 string	 name;

		//	Maximum	 key  size	for	 the  RC2  algorithm
		const  int	keySize	 =	128;

		//	Person	constructor
		public	Person(string  p_Name)
		{
			rsa	 =	new	 RSACryptoServiceProvider();
			rc2	 =	new	 RC2CryptoServiceProvider();
			rc2.KeySize	 =	keySize;
			name  =	 p_Name;
		}

		//	Used  to  send	the	 rsa  public  key  parameters
		public	RSAParameters  SendPublicKey()
		{
			RSAParameters  result  =  new  RSAParameters();
			try
			{
				result	=  rsa.ExportParameters(false);
			}
			catch  (CryptographicException	e)
			{
				Console.WriteLine(e.Message);
			}
			return	result;
		}

		//	Used  to  import  the  rsa	public	key	 parameters
		public	void  GetPublicKey(Person  receiver)
		{
			try
			{
				rsa.ImportParameters(receiver.SendPublicKey());
			}
			catch  (CryptographicException	e)
			{
				Console.WriteLine(e.Message);
			}
		}

		public	CipherMessage  EncryptMessage(string  text)
		{
			//	Convert	 string	 to	 a	byte  array
			CipherMessage  message	=  new	CipherMessage();
			byte[]	plainBytes	=  Encoding.Unicode.GetBytes(text.ToCharArray());

			//	A  new	key	 and  iv  are  generated  for  every  message
			rc2.GenerateKey();
			rc2.GenerateIV();

			//	The	 rc2  initialization  doesnt  need	to	be	encrypted,	but	 will
			//	be	used  in  conjunction  with	 the  key  to  decrypt	the	 message.
			message.rc2IV  =  rc2.IV;
			try
			{
				//	Encrypt	 the  RC2  key	using  RSA	encryption
				message.rc2Key	=  rsa.Encrypt(rc2.Key,	 false);
			}
			catch  (CryptographicException	e)
			{
				//	The	 High  Encryption  Pack	 is	 required  to  run	this	sample
				//	because	 we	 are  using	 a	128-bit	 key.  See	the	 readme	 for
				//	additional	information.
				Console.WriteLine("Encryption  Failed.  Ensure  that  the"  +
					"  High  Encryption  Pack  is  installed.");
				Console.WriteLine("Error  Message:  "  +  e.Message);
				Environment.Exit(0);
			}
			//	Encrypt	 the  Text	Message	 using	RC2	 (Symmetric	 algorithm)
			ICryptoTransform  sse  =  rc2.CreateEncryptor();
			MemoryStream  ms  =	 new  MemoryStream();
			CryptoStream  cs  =	 new  CryptoStream(ms,	sse,  CryptoStreamMode.Write);
			try
			{
					cs.Write(plainBytes,  0,  plainBytes.Length);
					cs.FlushFinalBlock();
					message.cipherBytes	 =	ms.ToArray();
			}
			catch  (Exception  e)
			{
					Console.WriteLine(e.Message);
			}
			finally
			{
				ms.Close();
				cs.Close();
			}
			return	message;
		}  //  method  EncryptMessage


		public	void  DecryptMessage(CipherMessage	message)
		{
			//	Get	 the  RC2  Key	and	 Initialization	 Vector
			rc2.IV	=  message.rc2IV;
			try
			{
				//	Try	 decrypting	 the  rc2  key
				rc2.Key	 =	rsa.Decrypt(message.rc2Key,	 false);
			}
			catch  (CryptographicException	e)
			{
				Console.WriteLine("Decryption  Failed:  "  +  e.Message);
				return;
			}

			ICryptoTransform  ssd  =  rc2.CreateDecryptor();
			//	Put	 the  encrypted	 message  in  a	 memorystream
			MemoryStream  ms  =	 new  MemoryStream(message.cipherBytes);
			//	the	 CryptoStream  will	 read  cipher  text	 from  the	MemoryStream
			CryptoStream  cs  =	 new  CryptoStream(ms,	ssd,  CryptoStreamMode.Read);
			byte[]	initialText	 =	new	 Byte[message.cipherBytes.Length];

			try
			{
					//	Decrypt	 the  message  and	store  in  byte	 array
					cs.Read(initialText,  0,  initialText.Length);
			}
			catch  (Exception  e)
			{
					Console.WriteLine(e.Message);
			}
			finally
			{
				ms.Close();
				cs.Close();
			}

			//	Display	 the  message  received
			Console.WriteLine(name	+  "  received  the  following  message:");
			Console.WriteLine("    "  +  Encoding.Unicode.GetString(initialText));
		}  //  method  DecryptMessage
	}  //  class  Person
}  //  namespace  PublicKey

辛苦了。。。但是貌似不是我想要的
FancyMouse 2013-04-28
  • 打赏
  • 举报
回复
引用 18 楼 fetag 的回复:
赵四你就别show下限了,越show人丢得越大~~ 第一个代码明晃晃的写着DES,第二个写着factor,这跟RSA八竿子都打不着的东西~~ 你要是不知道这些东西有什么区别,回去找本入门书读读然后再出来上蹿下跳吧~~
人节操早就掉光了。
独孤过儿 2013-04-28
  • 打赏
  • 举报
回复
赵四你就别show下限了,越show人丢得越大~~ 第一个代码明晃晃的写着DES,第二个写着factor,这跟RSA八竿子都打不着的东西~~ 你要是不知道这些东西有什么区别,回去找本入门书读读然后再出来上蹿下跳吧~~
赵4老师 2013-04-28
  • 打赏
  • 举报
回复
//******************************************************************************
// Author           :   Alexander Bell
// Copyright        :   2007-2011 Infosoft International Inc
// Date Created     :   01/15/2007
// Last Modified    :   02/08/2011
// Description      :   Prime Factoring
//******************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//******************************************************************************
//******************************************************************************
// TERMS OF USE     :   This module is copyrighted.
//                  :   You can use it at your sole risk provided that you keep
//                  :   the original copyright note.
//******************************************************************************
using System;
using System.Collections.Generic;
namespace Infosoft.MathShared
{
    /// <summary>Integers: Properties and Operations</summary>
     public  static partial class Integers
    {
        #region Prime Numbers <100
        private static readonly int[] Primes =
        new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23,
                    29, 31, 37, 41, 43, 47, 53, 59,
                    61, 67, 71, 73, 79, 83, 89, 97 };
        #endregion
         // starting number for iterative factorization
        private const int _startNum = 101;
        #region IsPrime: primality Check
        /// <summary>
        /// Check if the number is Prime
        /// </summary>
        /// <param name="Num">Int64</param>
        /// <returns>bool</returns>
        public static bool IsPrime(Int64 Num){
            int j;
            bool ret;
            Int64 _upMargin = (Int64)Math.Sqrt(Num) + 1; ;
            // Check if number is in Prime Array
            for (int i = 0; i < Primes.Length; i++){
                if (Num == Primes[i]) { return true; }
            }
            // Check divisibility w/Prime Array
            for (int i = 0; i < Primes.Length; i++) {
                if (Num % Primes[i] == 0) return false;
            }
            // Main iteration for Primality check
            _upMargin = (Int64)Math.Sqrt(Num) + 1;
            j = _startNum;
            ret = true;
            while (j <= _upMargin)
            {
                if (Num % j == 0) { ret = false; break; }
                else { j++; j++; }
            }
            return ret;
        }
        /// <summary>
        /// Check if number-string is Prime
        /// </summary>
        /// <param name="Num">string</param>
        /// <returns>bool</returns>
        public static bool IsPrime(string StringNum) {
            return IsPrime(Int64.Parse(StringNum));
        }
        #endregion
        #region Fast Factorization
        /// <summary>
        /// Factorize string converted to long integers
        /// </summary>
        /// <param name="StringNum">string</param>
        /// <returns>Int64[]</returns>
        public static Int64[] FactorizeFast(string StringNum) {
            return FactorizeFast(Int64.Parse(StringNum));
        }
        /// <summary>
        /// Factorize long integers: speed optimized
        /// </summary>
        /// <param name="Num">Int64</param>
        /// <returns>Int64[]</returns>
        public static Int64[] FactorizeFast(Int64 Num)
        {
            #region vars
            // list of Factors
            List<Int64> _arrFactors = new List<Int64>();
            // temp variable
            Int64 _num = Num;
            #endregion
            #region Check if the number is Prime (<100)
            for (int k = 0; k < Primes.Length; k++)
            {
                if (_num == Primes[k])
                {
                    _arrFactors.Add(Primes[k]);
                    return _arrFactors.ToArray();
                }
            }
            #endregion
            #region Try to factorize using Primes Array
            for (int k = 0; k < Primes.Length; k++)
            {
                int m = Primes[k];
                if (_num < m) break;
                while (_num % m == 0)
                {
                    _arrFactors.Add(m);
                    _num = (Int64)_num / m;
                }
            }
            if (_num < _startNum)
            {
                _arrFactors.Sort();
                return _arrFactors.ToArray();
            }
            #endregion
            #region Main Factorization Algorithm
            Int64 _upMargin = (Int64)Math.Sqrt(_num) + 1;
            Int64 i = _startNum;
            while (i <= _upMargin)
            {
                if (_num % i == 0)
                {
                    _arrFactors.Add(i);
                    _num = _num / i;
                    _upMargin = (Int64)Math.Sqrt(_num) + 1;
                    i = _startNum;
                }
                else { i++; i++; }
            }
            _arrFactors.Add(_num);
            _arrFactors.Sort();
            return _arrFactors.ToArray();
            #endregion
        }
        #endregion
    }
}
//******************************************************************************
fenggy0248 2013-04-28
  • 打赏
  • 举报
回复
引用 14 楼 fetag 的回复:
[quote=引用 13 楼 fenggy0248 的回复:] 2048,很简单么?我觉得好复杂,求指导啊
无非就那么几个步骤啊 1、先实现大数字相加、相乘、exponential modulo的算法,加乘简单可以忽略不计了。关于exponential modulo的可以用fast exponential modulo算法,你自己去google,到处都有解释 2、实现大数字的Euclidean Algorithm and Extended Euclidean Algorithm,这俩用来判断gcd和求multiplicative inverse 3、生成两个2048位的大素数,十进制是256位。用rand()%10的方法生成每一个,然后拼接成字符串 4、写个primality test算法,比如Miller-Rabin algorithm or Solovay-Strassen algorithm,然后对3中生成的数字进行判断 5、一个随机算法,生成private key,这步用到2中的算法来验证。 6、计算public key,根据2,5来求 7、加解密函数直接用1中的运算即可[/quote]原理明白,就是感觉实现起来有点痛苦
赵4老师 2013-04-28
  • 打赏
  • 举报
回复
using  System;
using  System.Security.Cryptography;
using  System.IO;
using  System.Text;

private	 byte[]	 Keys  =  {	 0xEF,	0xAB,  0x56,  0x78,	 0x90,	0x34,  0xCD,  0x12	};//默认密钥向量
///	 <summary>
///	 DES加密字符串
///	 </summary>
///	 <param	 name="encryptString">待加密的字符串</param>
///	 <param	 name="encryptKey">加密密钥,要求为8位</param>
///	 <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public	string	EncryptDES(string  encryptString,  string  encryptKey)
{
		try
		{
				byte[]	rgbKey	=  Encoding.UTF8.GetBytes(encryptKey.Substring(0,  8));
				byte[]	rgbIV  =  Keys;
				byte[]	inputByteArray	=  Encoding.UTF8.GetBytes(encryptString);
				DESCryptoServiceProvider  dCSP	=  new	DESCryptoServiceProvider();
				MemoryStream  mStream  =  new  MemoryStream();
				CryptoStream  cStream  =  new  CryptoStream(mStream,  dCSP.CreateEncryptor(rgbKey,	rgbIV),	 CryptoStreamMode.Write);
				cStream.Write(inputByteArray,  0,  inputByteArray.Length);
				cStream.FlushFinalBlock();
				return	Convert.ToBase64String(mStream.ToArray());
		}
		catch
		{
				return	encryptString;
		}
}

///	 <summary>
///	 DES解密字符串
///	 </summary>
///	 <param	 name="decryptString">待解密的字符串</param>
///	 <param	 name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
///	 <returns>解密成功返回解密后的字符串,失败返源串</returns>
public	string	DecryptDES(string  decryptString,  string  decryptKey)
{
		try
		{
				byte[]	rgbKey	=  Encoding.UTF8.GetBytes(decryptKey.Substring(0,  8));
				byte[]	rgbIV  =  Keys;
				byte[]	inputByteArray	=  Convert.FromBase64String(decryptString);
				DESCryptoServiceProvider  DCSP	=  new	DESCryptoServiceProvider();
				MemoryStream  mStream  =  new  MemoryStream();
				CryptoStream  cStream  =  new  CryptoStream(mStream,  DCSP.CreateDecryptor(rgbKey,	rgbIV),	 CryptoStreamMode.Write);
				cStream.Write(inputByteArray,  0,  inputByteArray.Length);
				cStream.FlushFinalBlock();
				return	Encoding.UTF8.GetString(mStream.ToArray());
		}
		catch
		{
				return	decryptString;
		}
}
///	 <summary>
///	 use  sha1	to	encrypt	 string
///	 </summary>
public	string	SHA1_Encrypt(string	 Source_String)
{
		byte[]	StrRes	=  Encoding.Default.GetBytes(Source_String);
		HashAlgorithm  iSHA	 =	new	 SHA1CryptoServiceProvider();
		StrRes	=  iSHA.ComputeHash(StrRes);
		StringBuilder  EnText  =  new  StringBuilder();
		foreach	 (byte	iByte  in  StrRes)
		{
				EnText.AppendFormat("{0:x2}",  iByte);
		}
		return	EnText.ToString();
}

namespace  Microsoft.Samples.Security.PublicKey
{
	class  App
	{
		//	Main  entry	 point
		static	void  Main(string[]	 args)
		{
			//	Instantiate	 3	People	for	 example.  See	the	 Person	 class	below
			Person	alice  =  new  Person("Alice");
			Person	bob	 =	new	 Person("Bob");
			Person	steve  =  new  Person("Steve");

			//	Messages  that	will  exchanged.  See  CipherMessage  class	 below
			CipherMessage  aliceMessage;
			CipherMessage  bobMessage;
			CipherMessage  steveMessage;

			//	Example	 of	 encrypting/decrypting	your  own  message
			Console.WriteLine("Encrypting/Decrypting  Your  Own  Message");
			Console.WriteLine("-----------------------------------------");

			//	Alice  encrypts	 a	message	 using	her	 own  public  key
			aliceMessage  =	 alice.EncryptMessage("Alice  wrote  this  message");
			//	then  using	 her  private  key	can	 decrypt  the  message
			alice.DecryptMessage(aliceMessage);
			//	Example	 of	 Exchanging	 Keys  and	Messages
			Console.WriteLine();
			Console.WriteLine("Exchanging  Keys  and  Messages");
			Console.WriteLine("-----------------------------------------");

			//	Alice  Sends  a	 copy  of  her	public	key	 to	 Bob  and  Steve
			bob.GetPublicKey(alice);
			steve.GetPublicKey(alice);

			//	Bob	 and  Steve	 both  encrypt	messages  to  send	to	Alice
			bobMessage	=  bob.EncryptMessage("Hi  Alice!  -  Bob.");
			steveMessage  =	 steve.EncryptMessage("How  are  you?  -  Steve");

			//	Alice  can	decrypt	 and  read	both  messages
			alice.DecryptMessage(bobMessage);
			alice.DecryptMessage(steveMessage);

			Console.WriteLine();
			Console.WriteLine("Private  Key  required  to  read  the  messages");
			Console.WriteLine("-----------------------------------------");

			//	Steve  cannot  read	 the  message  that	 Bob  encrypted
			steve.DecryptMessage(bobMessage);
			//	Not	 even  Bob	can	 use  the  Message	he	encrypted  for	Alice.
			//	The	 RSA  private  key	is	required  to  decrypt  the	RS2	 key  used
			//	in	the	 decryption.
			bob.DecryptMessage(bobMessage);

		}  //  method  Main
	}  //  class  App

	class  CipherMessage
	{
		public	byte[]	cipherBytes;	//	RC2	 encrypted	message	 text
		public	byte[]	rc2Key;				 //	 RSA  encrypted	 rc2  key
		public	byte[]	rc2IV;				  //  RC2  initialization  vector
	}

	class  Person
	{
		private	 RSACryptoServiceProvider  rsa;
		private	 RC2CryptoServiceProvider  rc2;
		private	 string	 name;

		//	Maximum	 key  size	for	 the  RC2  algorithm
		const  int	keySize	 =	128;

		//	Person	constructor
		public	Person(string  p_Name)
		{
			rsa	 =	new	 RSACryptoServiceProvider();
			rc2	 =	new	 RC2CryptoServiceProvider();
			rc2.KeySize	 =	keySize;
			name  =	 p_Name;
		}

		//	Used  to  send	the	 rsa  public  key  parameters
		public	RSAParameters  SendPublicKey()
		{
			RSAParameters  result  =  new  RSAParameters();
			try
			{
				result	=  rsa.ExportParameters(false);
			}
			catch  (CryptographicException	e)
			{
				Console.WriteLine(e.Message);
			}
			return	result;
		}

		//	Used  to  import  the  rsa	public	key	 parameters
		public	void  GetPublicKey(Person  receiver)
		{
			try
			{
				rsa.ImportParameters(receiver.SendPublicKey());
			}
			catch  (CryptographicException	e)
			{
				Console.WriteLine(e.Message);
			}
		}

		public	CipherMessage  EncryptMessage(string  text)
		{
			//	Convert	 string	 to	 a	byte  array
			CipherMessage  message	=  new	CipherMessage();
			byte[]	plainBytes	=  Encoding.Unicode.GetBytes(text.ToCharArray());

			//	A  new	key	 and  iv  are  generated  for  every  message
			rc2.GenerateKey();
			rc2.GenerateIV();

			//	The	 rc2  initialization  doesnt  need	to	be	encrypted,	but	 will
			//	be	used  in  conjunction  with	 the  key  to  decrypt	the	 message.
			message.rc2IV  =  rc2.IV;
			try
			{
				//	Encrypt	 the  RC2  key	using  RSA	encryption
				message.rc2Key	=  rsa.Encrypt(rc2.Key,	 false);
			}
			catch  (CryptographicException	e)
			{
				//	The	 High  Encryption  Pack	 is	 required  to  run	this	sample
				//	because	 we	 are  using	 a	128-bit	 key.  See	the	 readme	 for
				//	additional	information.
				Console.WriteLine("Encryption  Failed.  Ensure  that  the"  +
					"  High  Encryption  Pack  is  installed.");
				Console.WriteLine("Error  Message:  "  +  e.Message);
				Environment.Exit(0);
			}
			//	Encrypt	 the  Text	Message	 using	RC2	 (Symmetric	 algorithm)
			ICryptoTransform  sse  =  rc2.CreateEncryptor();
			MemoryStream  ms  =	 new  MemoryStream();
			CryptoStream  cs  =	 new  CryptoStream(ms,	sse,  CryptoStreamMode.Write);
			try
			{
					cs.Write(plainBytes,  0,  plainBytes.Length);
					cs.FlushFinalBlock();
					message.cipherBytes	 =	ms.ToArray();
			}
			catch  (Exception  e)
			{
					Console.WriteLine(e.Message);
			}
			finally
			{
				ms.Close();
				cs.Close();
			}
			return	message;
		}  //  method  EncryptMessage


		public	void  DecryptMessage(CipherMessage	message)
		{
			//	Get	 the  RC2  Key	and	 Initialization	 Vector
			rc2.IV	=  message.rc2IV;
			try
			{
				//	Try	 decrypting	 the  rc2  key
				rc2.Key	 =	rsa.Decrypt(message.rc2Key,	 false);
			}
			catch  (CryptographicException	e)
			{
				Console.WriteLine("Decryption  Failed:  "  +  e.Message);
				return;
			}

			ICryptoTransform  ssd  =  rc2.CreateDecryptor();
			//	Put	 the  encrypted	 message  in  a	 memorystream
			MemoryStream  ms  =	 new  MemoryStream(message.cipherBytes);
			//	the	 CryptoStream  will	 read  cipher  text	 from  the	MemoryStream
			CryptoStream  cs  =	 new  CryptoStream(ms,	ssd,  CryptoStreamMode.Read);
			byte[]	initialText	 =	new	 Byte[message.cipherBytes.Length];

			try
			{
					//	Decrypt	 the  message  and	store  in  byte	 array
					cs.Read(initialText,  0,  initialText.Length);
			}
			catch  (Exception  e)
			{
					Console.WriteLine(e.Message);
			}
			finally
			{
				ms.Close();
				cs.Close();
			}

			//	Display	 the  message  received
			Console.WriteLine(name	+  "  received  the  following  message:");
			Console.WriteLine("    "  +  Encoding.Unicode.GetString(initialText));
		}  //  method  DecryptMessage
	}  //  class  Person
}  //  namespace  PublicKey

独孤过儿 2013-04-28
  • 打赏
  • 举报
回复
引用 13 楼 fenggy0248 的回复:
2048,很简单么?我觉得好复杂,求指导啊
无非就那么几个步骤啊 1、先实现大数字相加、相乘、exponential modulo的算法,加乘简单可以忽略不计了。关于exponential modulo的可以用fast exponential modulo算法,你自己去google,到处都有解释 2、实现大数字的Euclidean Algorithm and Extended Euclidean Algorithm,这俩用来判断gcd和求multiplicative inverse 3、生成两个2048位的大素数,十进制是256位。用rand()%10的方法生成每一个,然后拼接成字符串 4、写个primality test算法,比如Miller-Rabin algorithm or Solovay-Strassen algorithm,然后对3中生成的数字进行判断 5、一个随机算法,生成private key,这步用到2中的算法来验证。 6、计算public key,根据2,5来求 7、加解密函数直接用1中的运算即可
fenggy0248 2013-04-28
  • 打赏
  • 举报
回复
引用 12 楼 fetag 的回复:
引用 10 楼 fenggy0248 的回复:
[quote=引用 2 楼 fthislife 的回复:] 有现成的大数库
毕设啊,直接用现成的,老师嫌工作量不够
毕设就实现个RSA???这也太容易了吧...[/quote]2048,很简单么?我觉得好复杂,求指导啊
独孤过儿 2013-04-28
  • 打赏
  • 举报
回复
引用 10 楼 fenggy0248 的回复:
引用 2 楼 fthislife 的回复:
有现成的大数库
毕设啊,直接用现成的,老师嫌工作量不够
毕设就实现个RSA???这也太容易了吧...
fenggy0248 2013-04-28
  • 打赏
  • 举报
回复
引用 9 楼 fetag 的回复:
[quote=引用 6 楼 zhao4zhong1 的回复:] [/code]
人不要脸,天下无敌! RSA是基于在非量子计算的环境下,没有polynomial time的算法能解决大数分解问题。你整个破数字运算的代码贴上来,骗得了你自己,就能骗别人了? RSA里面需要生成两个大素数,怎么生成?需要选择最大公因数是1的随机变量,怎么找?需要计算multiplicative inverse,怎么算?需要 exponential modulo操作,这又怎么做?你连RSA的原理都不懂,就敢胡乱给人贴风马牛不相及的代码?典型的神棍!为了骗分,完全丧尽天良! 楼主可以用GMP或者NTL这两个库,他们提供了支撑密码学的数据类型和函数。利用这些可以很方便的实现基于 大数分解、离散对数、椭圆曲线、lattices reduction 等这些理论的算法。 [/quote]毕设啊,直接用现成的,老师嫌工作量不够
fenggy0248 2013-04-28
  • 打赏
  • 举报
回复
引用 2 楼 fthislife 的回复:
有现成的大数库
毕设啊,直接用现成的,老师嫌工作量不够
独孤过儿 2013-04-28
  • 打赏
  • 举报
回复
引用 6 楼 zhao4zhong1 的回复:
[/code]
人不要脸,天下无敌! RSA是基于在非量子计算的环境下,没有polynomial time的算法能解决大数分解问题。你整个破数字运算的代码贴上来,骗得了你自己,就能骗别人了? RSA里面需要生成两个大素数,怎么生成?需要选择最大公因数是1的随机变量,怎么找?需要计算multiplicative inverse,怎么算?需要 exponential modulo操作,这又怎么做?你连RSA的原理都不懂,就敢胡乱给人贴风马牛不相及的代码?典型的神棍!为了骗分,完全丧尽天良! 楼主可以用GMP或者NTL这两个库,他们提供了支撑密码学的数据类型和函数。利用这些可以很方便的实现基于 大数分解、离散对数、椭圆曲线、lattices reduction 等这些理论的算法。
就是那个党伟 2013-04-28
  • 打赏
  • 举报
回复
6楼,目测可行!
yuanhong2910 2013-04-28
  • 打赏
  • 举报
回复
好多库呢,botan, crypto++, 好像openSSL都可以。
lsjfdjoijvtghu 2013-04-27
  • 打赏
  • 举报
回复
插一块超大内存条
flyrack 2013-04-27
  • 打赏
  • 举报
回复
大数库写起来就够呛了
healer_kx 2013-04-27
  • 打赏
  • 举报
回复
为什么要自己实现呢?有这个必要吗?我不反对造轮子,但是这个轮子似乎。。。
加载更多回复(2)
课程简介    随着”新基建“的推行,其中涉及到的工业互联网、物联网、人工智能、云计算、区块链,无一不是与安全相关,所有数据的存储、传输、签名认证都涉及到密码学技术,所以在这样的大环境下再结合我多年安全开发经验,设计出这门课程。    因为密码学技术在新基建中的重要性,所以使其成为底层开发人员所必备的技能。特别是现在的区块链技术是全面应用密码学,大数据技术和人工智能技术也要解决隐私安全问题。所以现在学习相关技术是非常必要的技术储备,并且可以改造现有的系统,提升其安全性。课程学习目标了解DES算法原理VS2019创建C++项目,并导入openssl库学会OpenSSL DES算法加解密接口加密文件并做PKCS7 Padding 数据填充解密数据并做数据填充解析课程特点    面向工程应用    市面上的一些密码学课程和密码学的书籍,很多都是从考证出发,讲解算法原理并不面向工程应用,而我们现在缺少的是工程应用相关的知识,本课程从工程应用出发,每种技术都主要讲解其在工程中的使用,并演示工程应用的代码。    从零实现部分算法    课程中实现了base16编解码 ,XOR对称加解密算法,PKCS7 pading数据填充算法,通过对一些简单算法实现,从而加深对密码学的理解。    理论与实践结合    课程如果只是讲代码,同学并不能理解接口背后的原理,在项目设计中就会留下隐患,出现错误也不容易排查出问题。    如果只讲理论,比如对密码学的一些研究,对于大部分从事工程应用的同学并没有必要,而是理论与实践结合,一切为了工程实践。    代码现场打出    代码不放在ppt而是现场打出,更好的让学员理解代码编写的逻辑,老师现场敲出代码正是展示出了工程项目的思考,每个步骤为什么要这么做,考虑了哪些异常,    易学不枯燥    课程为了确保大部分人开发者都学得会,理解算法原理(才能真正理解算法特性),学会工程应用(接口调用,但不局限接口调用,理解接口背后的机制,并能解决工程中会出现的问题),阅读算法源码但不实现密码算法,,并能将密码学投入到实际工程中,如果是想学习具体的加密算法实现,请关注我后面的课程。课程用到的技术    课程主要演示基于 VS2019 C++,部分演示基于ubuntu 18.04 GCC makefile    如果没有装linux系统,对本课程的学习也没有影响    课程中的OpenSSL基于最新的3.0版本,如果是openss 1.1.1版本也支持,再低的版本不支持国密算法。 课程常见问题课程讲解用的什么平台和工具?    课程演示主要在windows,基于VS2019 ,一些项目会移植到Linux在ubuntu18.04上我不会Linux能否学习本门课程?    可以的,课程主要在Windows上,Linux部分只是移植,可以暂时跳过,熟悉了Linux再过来看我不会C/C++ 语言是否能学习本门课程?    至少要会C语言,C++特性用得不多,但做了一个封装,可以预习一些C++基础。会不会讲算法实现,会不会太难学不会?    课程偏工程应用,具体的AES,椭圆曲线、RSA算法只通过图示讲原理,一些简单hash算法会读一些源码,并不去实现,课程中会单独实现简洁的XOR对称加密和base16算法(代码量不大易懂)。其他的应用我们都基于OpenSSL3.0的SDK调用算法。课程提供源码和PPT吗?    课程中所有讲解的源码都提供,课程的上课的ppt也提供,PPT提供pdf版,只可以用于学习,不得商用,代码可以用于商用软件项目,涉及到开源系统部分,需要遵守开源的协议,但不得用于网络教学。要观看全部内容请点击c++实战区块链核心密码学-基于opensslhttps://edu.csdn.net/course/play/29593

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧