ilovecomputer66 发表于 2023-2-16 10:34

求个C#客户端、Java服务器都支持 RSA/CBC/PKCS1Padding 加解密的代码,实现互加密互解

网上找的教程,几乎都不考虑分段加密解密,数据大一点点,就不能用(比如,都是抄这个没考虑分段加密的) https://blog.csdn.net/thc1987/article/details/81383365

我只找到客户端分段加密的,但是代码有缺陷,只能用ECB,不能CBC,否则报错(不知为何)https://blog.csdn.net/Qin066/article/details/121856447

java的木有找到支持分段加密,并且和上面C#代码能配合的

ttyy008 发表于 2023-2-16 14:19

Bouncy Castle这个库,参考:https://www.bouncycastle.org/csharp/index.html

ilovecomputer66 发表于 2023-2-16 14:43

ttyy008 发表于 2023-2-16 14:19
Bouncy Castle这个库,参考:https://www.bouncycastle.org/csharp/index.html
额,我上面那个https://blog.csdn.net/Qin066/article/details/121856447

就是用这个库呀,现在网上资料全都用这个的。但问题不是在用什么库,而是怎么用。我没有找到用这个库,可以用CBC方式的写法,都是ECB的(已被证明不安全,不推荐)

ttyy008 发表于 2023-2-16 22:56

试试吧
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using System;
using System.Text;

public class Program
{
    static void Main(string[] args)
    {      
      byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef");
      byte[] iv = Encoding.UTF8.GetBytes("fedcba9876543210");

      
      string plaintext = "Hello, world!";
      
      byte[] ciphertext = EncryptCBC(Encoding.UTF8.GetBytes(plaintext), key, iv);
      
      string ciphertextString = Convert.ToBase64String(ciphertext);
      Console.WriteLine("Ciphertext: " + ciphertextString);

   
      byte[] decrypted = DecryptCBC(ciphertext, key, iv);
      
      string decryptedString = Encoding.UTF8.GetString(decrypted);
      Console.WriteLine("Decrypted: " + decryptedString);
    }

    public static byte[] EncryptCBC(byte[] plaintext, byte[] key, byte[] iv)
    {      
      IBlockCipher cipher = new AesFastEngine();
      cipher = new CbcBlockCipher(cipher);
      cipher = new PaddedBufferedBlockCipher(cipher);

      cipher.Init(true, new ParametersWithIV(new KeyParameter(key), iv));
      
      byte[] output = new byte;
      int bytesProcessed = cipher.ProcessBytes(plaintext, 0, plaintext.Length, output, 0);
      cipher.DoFinal(output, bytesProcessed);

      return output;
    }

    public static byte[] DecryptCBC(byte[] ciphertext, byte[] key, byte[] iv)
    {      
      IBlockCipher cipher = new AesFastEngine();
      cipher = new CbcBlockCipher(cipher);
      cipher = new PaddedBufferedBlockCipher(cipher);

      cipher.Init(false, new ParametersWithIV(new KeyParameter(key), iv));
      
      byte[] output = new byte;
      int bytesProcessed = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, output, 0);
      cipher.DoFinal(output, bytesProcessed);

      return output;
    }
}
页: [1]
查看完整版本: 求个C#客户端、Java服务器都支持 RSA/CBC/PKCS1Padding 加解密的代码,实现互加密互解