Public Key RSA Encryption in C# .NET

本文介绍RSA加密的基本原理及其在.NET框架中的实现方式。包括RSA加密算法的背景、密钥生成过程及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://www.codeproject.com/Articles/10877/Public-Key-RSA-Encryption-in-C-NET

General Information


RSACryptoPad is a very basic display of the RSA encryption abilities in the .NET framework libraries. This code will use public key RSA encryption presented in a notepad-style program. You know…spy stuff. :-)

Your best resource for RSA encryption is RSA Security.

The way you use this code is to change it to suit your purposes and/or take pieces of it to use in your own program. There are encryption projects on CodeProject already but I am sure you'll see the difference in what I am doing.

I realize to be productive you may want to skip the details of this program and utilize only the main encryption functions. So, here is a quick listing of them:

public string EncryptString( string inputString, int dwKeySize, 
                             string xmlString )
{
    // TODO: Add Proper Exception Handlers
    RSACryptoServiceProvider rsaCryptoServiceProvider = 
                                  new RSACryptoServiceProvider( dwKeySize );
    rsaCryptoServiceProvider.FromXmlString( xmlString );
    int keySize = dwKeySize / 8;
    byte[] bytes = Encoding.UTF32.GetBytes( inputString );
    // The hash function in use by the .NET RSACryptoServiceProvider here 
    // is SHA1
    // int maxLength = ( keySize ) - 2 - 
    //              ( 2 * SHA1.Create().ComputeHash( rawBytes ).Length );
    int maxLength = keySize - 42;
    int dataLength = bytes.Length;
    int iterations = dataLength / maxLength;
    StringBuilder stringBuilder = new StringBuilder();
    for( int i = 0; i <= iterations; i++ )
    {
        byte[] tempBytes = new byte[ 
                ( dataLength - maxLength * i > maxLength ) ? maxLength : 
                                              dataLength - maxLength * i ];
        Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, 
                          tempBytes.Length );
        byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes,
                                                                  true );
        // Be aware the RSACryptoServiceProvider reverses the order of 
        // encrypted bytes. It does this after encryption and before 
        // decryption. If you do not require compatibility with Microsoft 
        // Cryptographic API (CAPI) and/or other vendors. Comment out the 
        // next line and the corresponding one in the DecryptString function.
        Array.Reverse( encryptedBytes );
        // Why convert to base 64?
        // Because it is the largest power-of-two base printable using only 
        // ASCII characters
        stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );
    }
    return stringBuilder.ToString();
}

public string DecryptString( string inputString, int dwKeySize, 
                             string xmlString )
{
    // TODO: Add Proper Exception Handlers
    RSACryptoServiceProvider rsaCryptoServiceProvider
                             = new RSACryptoServiceProvider( dwKeySize );
    rsaCryptoServiceProvider.FromXmlString( xmlString );
    int base64BlockSize = ( ( dwKeySize / 8 ) % 3 != 0 ) ?
      ( ( ( dwKeySize / 8 ) / 3 ) * 4 ) + 4 : ( ( dwKeySize / 8 ) / 3 ) * 4;
    int iterations = inputString.Length / base64BlockSize; 
    ArrayList arrayList = new ArrayList();
    for( int i = 0; i < iterations; i++ )
    {
        byte[] encryptedBytes = Convert.FromBase64String( 
             inputString.Substring( base64BlockSize * i, base64BlockSize ) );
        // Be aware the RSACryptoServiceProvider reverses the order of 
        // encrypted bytes after encryption and before decryption.
        // If you do not require compatibility with Microsoft Cryptographic 
        // API (CAPI) and/or other vendors.
        // Comment out the next line and the corresponding one in the 
        // EncryptString function.
        Array.Reverse( encryptedBytes );
        arrayList.AddRange( rsaCryptoServiceProvider.Decrypt( 
                            encryptedBytes, true ) );
    }
    return Encoding.UTF32.GetString( arrayList.ToArray( 
                              Type.GetType( "System.Byte" ) ) as byte[] );
}

The following tutorial is provided if you feel you want to know a little more about RSA cryptography.

RSA Cryptography Tutorial

The security of a cryptographic system should not be based on the privacy of its implementation. It should be based on the strength of its underlying mathematical cryptographic algorithm. An algorithm is a procedure or formula. The challenge of any cryptographic algorithm is to stand the test of time once the “collective masses” know everything about its implementation.

RSA cryptography is named after its inventors Ron Rivest, Adi Shamir, and Len Adleman. However, the idea was first discovered in 1973 by a member of the British government named Clifford c***s.

A few months prior to the writing of this article a successful factorization of a 193-digit prime number which in this case was a RSA 640-bit encryption key has been factored successfully by a research team comprised of F. Bahr, M. Boehm, J. Franke, and T. Kleinjung. The effort took approximately 30 2.2GHz-Opteron-CPU years which is over five months of calendar time according to the submitters.

In order to understand that last statement it is necessary to know that factorization is the resolution of an integer into “factors” and that cryptographic keys are very large numbers measured in “bits” which represent the binary digits it takes to compose the number. This is significant because it means that 640-bit and lower RSA encryption keys are no longer completely secure.

The mention of the word “cryptography” elicits many varying reactions. Some of the reactions you may receive are: boredom, confusion, concern, and maybe even fear. The reason for this emotional reaction is based on the relative significance to the individual.

In cryptography, everything starts with data that can be read without any extra effort referred to as "plain-text". The method of converting plain-text into unreadable gibberish called “cipher-text” is encryption. The process of reverting this gibberish back into the original plain-text is called decryption. Simply stated, cryptography is the science of using mathematics to scramble and descramble information. Cryptography allows the storage and transmission of sensitive material so that it can only be read by the intended recipient.

How cryptography works is by the use of cryptographic algorithms called “ciphers” and “deciphers”, which are mathematical functions that work with cryptographic keys to encrypt and decrypt plain-text. The bigger the key, the more secure the cipher-text. The same plain-text encrypts to different cipher-text with different keys.

Public key cryptography utilizes a public key for encryption as well as a corresponding private key for decryption. Because it uses two differing keys, it is sometimes called asymmetric cryptography. Asymmetric means unbalanced or different. While the public and private keys are mathematically related, it is computationally infeasible to deduce the private key from the public key, which requires factoring large prime numbers, without massive amounts of computing power. The primary advantage of public key cryptography is that it allows people who have no preexisting arrangement with you to exchange data securely. You publish your public key to the world while keeping your private key secret. Anyone with a copy of your public key can then encrypt information that only you can decrypt with your private key.

Base-64 Numbers

Throughout cryptography, you will see often see numbers represented as large character strings. For example, a RSAModulus, which is a part of a RSA public key, may appear as follows:

6nfX01TUfFaliu1wit5RJ5JQNFBzxWSePsviImlPKReIFSjpktWW6RbGk4pNj+fqh2DOWquaMzdXI27YFVuFJQ==

Do not let the cryptic stuff discourage you. This string of characters is really just a very large number represented in a way with which you may not be familiar. This number has been converted to a base-64 number. To understand base-64 encoded numbers, begin by recalling elementary school math. When we first learned about numbers, we were taught that, in the decimal system (base-10), things are organized into columns:

Hundreds|Tens|Ones
1 9 3

Therefore, the number "193" is 1-hundreds plus 9-tens plus 3-ones. Years later, we learned that the ones column meant 100, the tens column meant 101, the hundreds column 102 and so on, so the number 193 is really:

{ ( 1 * 10<sup>2 </sup>) + ( 9 * 10<sup>1 </sup>) + ( 3 * 10<sup>0 </sup>) }

The base-64 numbering system works under the exact same principles as the decimal system, only it operates in base-64 rather than base-10. In other words, instead of columns being:

10<sup>2</sup>|10<sup>1</sup>|10<sup>0</sup>

They are:

64<sup>2</sup>|64<sup>1</sup>|64<sup>0</sup>

Since there are not enough numbers to properly represent the numbers we are creating, letters are used as well. Here is a quick break down of what the letters represent:

0-25 is 'A'-'Z'
26-51 is 'a'-'z'
52-61 is '0'-'9'
62 is '+'
63 is '/'
Pad is '='

In order to understand public key cryptography it is necessary to understand what composes the encryption components. I do not implement the following processes in my program as they are already provided in the .NET framework. However, I felt a description of the process was necessary. An RSA private key may have two representations. However, only the one demonstrated in this article's corresponding programming projectRSACryptoPad that uses the Chinese remainder theorem1 is explained here. In order to generate better understanding I have used plain English rather than modular arithmetic formulas wherever possible.

Skipping a lot of detail, here is the procedure for creating the RSA components:

  1. Generate two different large odd prime numbers, called P and Q, of about the same size where P is greater than Q that when multiplied together give a product that can be represented by the required bit length you have chosen, e.g. 1024 bits. These numbers are used to create your Modulus.
  2. Choose an Exponent that is greater than three, and less than Modulus - 1. Exponent does not have to be prime, but it has to be odd. ( P – 1 ) * ( Q – 1 ) can't be prime because it's an even number. Then ensure that the greatest common denominator of Exponent and the least common multiple of P – 1 and Q – 1 equal 1.
  3. To create D the private exponent simply find an integer X which causes D = ( X * ( ( P – 1 ) * ( Q – 1 ) ) + 1 ) / E to be an integer, then use that value for D.
  4. The following key components DP, DQ, and InverseQ are found with the following formulas2 (all components are positive integers where P>Q):
    • DP = ( 1 / Exponent) mod ( P - 1 )
    • DQ = (1 / Exponent ) mod ( Q - 1 )
    • InverseQ = ( 1 / Q ) mod P where P > Q

When representing the plain-text to plain-text octets in order to secure the message more thoroughly it is usual to add padding characters to make it less susceptible to certain types of attack. I leave this one for your further research. After all that has been accomplished you have public and private keys ready for encryption which are then stored as base-64 numbers.

The following is a very generalized explanation of the encryption and decryption functions, the cipher is the encryption function and the decipher is the decryption function2.

The encryption function is:

C = ( TExponent ) mod Modulus, where C is the cipher-text (a positive integer), and T is the plain-text (a positive integer). T the plain-text being encrypted must be less than the Modulus.

The decryption function is:

The decryption function is T = (CD) mod Modulus, where C is the cipher-text (a positive integer), T is the plain-text (a positive integer). D is the secret exponent.

You can publish your public key to the world freely, because there are no known quick methods of calculating your D, P, and Q.

In conclusion, I included a program written C# using the .NET Framework libraries which implement RSAcryptography.

History

The Microsoft Cryptographic Service Provider Programmer's Guide was used as my reference material and it is written in C#. This little program was originally written in Visual Studio 2003 with .NET Framework v1.1 which may still function. However, I was using Microsoft Visual C# 2005 Express Edition to update this code. So, I only know only of its ability to function with .NET v2.0. This program requires Windows XP/Server 2003. The following enhancements have been made since the last version:

  • Removed some functionality invalid in .NET 2.0
  • Enhanced the encryption functions to handle any valid .NET key length
  • Added code to save form settings
  • Added drag and drop functionality

1 For a thorough explanation of the Chinese remainder theorem, please refer to [RSA02].

2 For a thorough explanation of modular arithmetic, please refer to [RSA02].

References

  • [COX73] Clifford c***s. A note on 'Non-Secret Encryption', CESG research report, 20th November 1973.
  • [RSA04] RSA Laboratories. RSA Security - The RSA Challenge Numbers, 2004.
  • [PGP04] PGP Corporation, An introduction to cryptography. PGP Corporation, 2004.
  • [MSC96] Microsoft Corporation, Microsoft Cryptographic Service Provider Programmer's Guide, Microsoft Corporation, 1996.
  • [RSA02] RSA Laboratories. PKCS #1 v2.1: RSA Encryption Standard, 2002.
  • [RSA78] R. Rivest, A. Shamir, and L. Adleman. A method for obtaining digital signatures and public-key cryptosystems. Communications of the ACM, 21 (2), pp. 120-126, 1978.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

内容概要:本文针对火电厂参与直购交易挤占风电上网空间的问题,提出了一种风火打捆参与大用户直购交易的新模式。通过分析可再生能源配额机制下的双边博弈关系,建立了基于动态非合作博弈理论的博弈模型,以直购电价和直购电量为决策变量,实现双方收益均衡最大化。论文论证了纳什均衡的存在性,并提出了基于纳什谈判法的风-火利益分配方法。算例结果表明,该模式能够增加各方收益、促进风电消纳并提高电网灵活性。文中详细介绍了模型构建、成本计算和博弈均衡的实现过程,并通过Python代码复现了模型,包括参数定义、收益函数、纳什均衡求解、利益分配及可视化分析等功能。 适合人群:电力系统研究人员、能源政策制定者、从事电力市场交易的工程师和分析师。 使用场景及目标:①帮助理解风火打捆参与大用户直购交易的博弈机制;②为电力市场设计提供理论依据和技术支持;③评估不同政策(如可再生能源配额)对电力市场的影响;④通过代码实现和可视化工具辅助教学和研究。 其他说明:该研究不仅提供了理论分析,还通过详细的代码实现和算例验证了模型的有效性,为实际应用提供了参考。此外,论文还探讨了不同场景下的敏感性分析,如证书价格、风电比例等对市场结果的影响,进一步丰富了研究内容。
资源下载链接为: https://pan.quark.cn/s/d37d4dbee12c A:计算机视觉,作为人工智能领域的关键分支,致力于赋予计算机系统 “看懂” 世界的能力,从图像、视频等视觉数据中提取有用信息并据此决策。 其发展历程颇为漫长。早期图像处理技术为其奠基,后续逐步探索三维信息提取,与人工智能结合,又经历数学理论深化、机器学习兴起,直至当下深度学习引领浪潮。如今,图像生成和合成技术不断发展,让计算机视觉更深入人们的日常生活。 计算机视觉综合了图像处理、机器学习、模式识别和深度学习等技术。深度学习兴起后,卷积神经网络成为核心工具,能自动提炼复杂图像特征。它的工作流程,首先是图像获取,用相机等设备捕获视觉信息并数字化;接着进行预处理,通过滤波、去噪等操作提升图像质量;然后进入关键的特征提取和描述环节,提炼图像关键信息;之后利用这些信息训练模型,学习视觉模式和规律;最终用于模式识别、分类、对象检测等实际应用。 在实际应用中,计算机视觉用途极为广泛。在安防领域,能进行人脸识别、目标跟踪,保障公共安全;在自动驾驶领域,帮助车辆识别道路、行人、交通标志,实现安全行驶;在医疗领域,辅助医生分析医学影像,进行疾病诊断;在工业领域,用于产品质量检测、机器人操作引导等。 不过,计算机视觉发展也面临挑战。比如图像生成技术带来深度伪造风险,虚假图像和视频可能误导大众、扰乱秩序。为此,各界积极研究检测技术,以应对这一问题。随着技术持续进步,计算机视觉有望在更多领域发挥更大作用,进一步改变人们的生活和工作方式 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值