RSA加解密简单实现( 二 )


需要加密的字节数不能超过密钥的长度值除以 8 再减去 11(ider. / 8 - 11),而加密后得到密文的字节数,正好是密钥的长度值除以 8(即:ider. / 8)
因此对于加密/解密数据长度超过最大长度限制时,使用分块加密/解密的方式
分块加密实现
/// /// 获取RSA私钥加密数据/// /// 加密公钥/// 加密原文数据/// public string GetRSAEncrypt(string publicKey,string txtValue){byte[] publicKeyByte = Convert.FromBase64String(publicKey);int publicBytesRead = 0;RSACryptoServiceProvider rsaPublic = new RSACryptoServiceProvider();rsaPublic.ImportRSAPublicKey(publicKeyByte, out publicBytesRead);int maxBlockSize = rsaPublic.KeySize / 8 - 11;//加密块最大长度限制//公钥加密string enStr = "";byte[] jsonByte = System.Text.Encoding.UTF8.GetBytes(txtValue);if (jsonByte.Length <= maxBlockSize){enStr = Convert.ToBase64String(rsaPublic.Encrypt(jsonByte, RSAEncryptionPadding.Pkcs1));}else{//待加密的字节数不能超过密钥的长度值除以 8 再减去 11(即:RSACryptoServiceProvider.KeySize / 8 - 11),//而加密后得到密文的字节数,正好是密钥的长度值除以 8(即:RSACryptoServiceProvider.KeySize / 8) 。//加密数据长度超过最大长度限制时,使用分块加密的方式using (MemoryStream plaiStream = new MemoryStream(jsonByte))using (MemoryStream crypStream = new MemoryStream()){byte[] buffer = new byte[maxBlockSize];int blockSize = plaiStream.Read(buffer, 0, maxBlockSize);while (blockSize > 0){byte[] toEncrypt = new byte[blockSize];Array.Copy(buffer, 0, toEncrypt, 0, blockSize);byte[] cryptograph = rsaPublic.Encrypt(toEncrypt, RSAEncryptionPadding.Pkcs1);crypStream.Write(cryptograph, 0, cryptograph.Length);blockSize = plaiStream.Read(buffer, 0, maxBlockSize);}enStr = Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None);}}return enStr;}
分块解密实现
/// /// RSA解密/// /// 密文数据/// 解密私钥/// public string DeRsaData(string cipherText, string privateKey){string deStr = "";int bytesRead = 0;RSACryptoServiceProvider rsaPrivate = new RSACryptoServiceProvider();rsaPrivate.ImportRSAPrivateKey(Convert.FromBase64String(privateKey), out bytesRead);int maxBlockSize = rsaPrivate.KeySize / 8; //解密块最大长度限制byte[] ciphertextData = http://www.kingceram.com/post/Convert.FromBase64String(cipherText);if (ciphertextData.Length <= maxBlockSize){deStr = System.Text.Encoding.UTF8.GetString(rsaPrivate.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));}else{//需要解密的数据长度超过解密块最大长度时,使用分块解密using (MemoryStream crypStream = new MemoryStream(ciphertextData))using (MemoryStream plaiStream = new MemoryStream()){byte[] buffer = new byte[maxBlockSize];int blockSize = crypStream.Read(buffer, 0, maxBlockSize);while (blockSize> 0){byte[] toDecrypt = new byte[blockSize];Array.Copy(buffer, 0, toDecrypt, 0, blockSize);byte[] plaintext = rsaPrivate.Decrypt(toDecrypt, RSAEncryptionPadding.Pkcs1);plaiStream.Write(plaintext, 0, plaintext.Length);blockSize = crypStream.Read(buffer, 0, maxBlockSize);}deStr = System.Text.Encoding.UTF8.GetString(plaiStream.ToArray());}}return deStr;}
附录
【RSA加解密简单实现】关于..的使用学习ider 类 (..) |Learn