当前位置: 首页 > 知识库问答 >
问题:

读C#和Bouncy Castle中的RSA PrivateKey

韩刚洁
2023-03-14

我已经成功地用OpenSSL格式写入了公钥和私钥文件。

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpHCHYgawzNlxVebSKXL7vfc/i
hP+dQgMxlaPEi7/vpQtV2szHjIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7
SRXaGVggqQEKH+cRi5+UcEObIfpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZO
ZxamOrWWL8KGB+lH+QIDAQAB
-----END PUBLIC KEY-----

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCpHCHYgawzNlxVebSKXL7vfc/ihP+dQgMxlaPEi7/vpQtV2szH
jIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7SRXaGVggqQEKH+cRi5+UcEOb
Ifpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZOZxamOrWWL8KGB+lH+QIDAQAB
AoGBAIXtL6jFWVjdjlZrIl4JgXUtkDt21PD33IuiVKZNft4NOWLu+wp17/WZYn3S
C2fbSXfaKZIycKi0K8Ab6zcUo0+QZKMoaG5GivnqqTPVAuZchkuMUSVgjGvKAC/D
12/b+w+Shs9pvqED1CxfvtePXNwL6ZNuaREFC5hF/YpMVyg5AkEA3BUCZYJ+Ec96
2cwsdY6HocW8Kn+RIqMjkNtyLA19cQV5mpIP7kAiW6drBDlraVANi+5AgK2zQ+ZT
hYzs/JfRKwJBAMS1g5/B7XXnfC6VTRs8AMveZudi5wS/aGpaApybsfx1NTLLsm3l
GmGTkbCr+EPzvJ5zRSIAHAA6N6NdORwzEWsCQHTli+JTD5dyNvScaDkAvbYFi06f
d32IXYnBpcEUYT65A8BAOMn5ssYwBL23qf/ED431vLkcig1Ut6RGGFKKaQUCQEfa
UdkSWm39/5N4f/DZyySs+YO90csfK8HlXRzdlnc0TRlf5K5VyHwqDkatmoMfzh9G
1dLknVXL7jTjQZA2az8CQG0jRSQ599zllylMPPVibW98701Mdhb1u20p1fAOkIrz
+BNEdOPqPVIyqIP830nnFsJJgTG2eKB59ym+ypffRmA=
-----END RSA PRIVATE KEY-----
public static AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
    var fileStream = System.IO.File.OpenText(pemFilename);
    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
    var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
    return KeyParameter;
}

static void Encrypt2(string publicKeyFileName, string inputMessage, string encryptedFileName)
    {   
        UTF8Encoding utf8enc = new UTF8Encoding();
        FileStream encryptedFile = null;

        try
        {
            // Converting the string message to byte array
            byte[] inputBytes = utf8enc.GetBytes(inputMessage);

            // RSAKeyPairGenerator generates the RSA Key pair based on the random number and strength of key required
            /*RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
            rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
            */

            AsymmetricKeyParameter publicKey = ReadAsymmetricKeyParameter(publicKeyFileName);

            // Creating the RSA algorithm object
            IAsymmetricBlockCipher cipher = new RsaEngine();

            // Initializing the RSA object for Encryption with RSA public key. Remember, for encryption, public key is needed
            cipher.Init(true, publicKey);

            //Encrypting the input bytes
            byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);

            //Write the encrypted message to file
            // Write encrypted text to file
            encryptedFile = File.Create(encryptedFileName);
            encryptedFile.Write(cipheredBytes, 0, cipheredBytes.Length);
        }
        catch (Exception ex)
        {
            // Any errors? Show them
            Console.WriteLine("Exception encrypting file! More info:");
            Console.WriteLine(ex.Message);
        }
        finally
        {
            // Do some clean up if needed
            if (encryptedFile != null)
            {
                encryptedFile.Close();
            }
        }

    }
static void Decrypt2(string privateKeyFileName, string encryptedFileName, string plainTextFileName)
    {
        UTF8Encoding utf8enc = new UTF8Encoding();
        FileStream encryptedFile = null;
        StreamWriter plainFile = null;
        byte[] encryptedBytes = null;
        string plainText = "";

        try
        {
            // Converting the string message to byte array
            //byte[] inputBytes = utf8enc.GetBytes(inputMessage);

            // RSAKeyPairGenerator generates the RSA Key pair based on the random number and strength of key required
            /*RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
            rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 512));
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
            */


            StreamReader sr = File.OpenText(privateKeyFileName);
            PemReader pr = new PemReader(sr);

            PemReader pemReader = new PemReader(new StringReader(privateKeyFileName));
            AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
            Console.WriteLine(keyPair.ToString());
            AsymmetricKeyParameter privatekey = keyPair.Private;


            Console.WriteLine(pr.ReadPemObject());
            AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();

            AsymmetricKeyParameter privateKey = ReadAsymmetricKeyParameter(privateKeyFileName);

            // Creating the RSA algorithm object
            IAsymmetricBlockCipher cipher = new RsaEngine();
            Console.WriteLine("privateKey: " + privateKey.ToString());

            // Initializing the RSA object for Decryption with RSA private key. Remember, for decryption, private key is needed
            //cipher.Init(false, KeyPair.Private);
            //cipher.Init(false, KeyPair.Private);
            cipher.Init(false, keyPair.Private);    

            // Read encrypted text from file
            encryptedFile = File.OpenRead(encryptedFileName);
            encryptedBytes = new byte[encryptedFile.Length];
            encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length);

            //Encrypting the input bytes
            //byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
            byte[] cipheredBytes = cipher.ProcessBlock(encryptedBytes, 0, encryptedBytes.Length);

            //Write the encrypted message to file
            // Write encrypted text to file
            plainFile = File.CreateText(plainTextFileName);
            plainText = Encoding.Unicode.GetString(cipheredBytes);
            plainFile.Write(plainText);
        }
        catch (Exception ex)
        {
            // Any errors? Show them
            Console.WriteLine("Exception encrypting file! More info:");
            Console.WriteLine(ex.Message);
        }
        finally
        {
            // Do some clean up if needed
            if (plainFile != null)
            {
                plainFile.Close();
            }
            if (encryptedFile != null)
            {
                encryptedFile.Close();
            }
        }
    }


    // Decrypt a file
    static void Decrypt(string privateKeyFileName, string encryptedFileName, string plainFileName)
    {
        // Variables
        CspParameters cspParams = null;
        RSACryptoServiceProvider rsaProvider = null;
        StreamReader privateKeyFile = null;
        FileStream encryptedFile = null;
        StreamWriter plainFile = null;
        string privateKeyText = "";
        string plainText = "";
        byte[] encryptedBytes = null;
        byte[] plainBytes = null;

        try
        {
            // Select target CSP
            cspParams = new CspParameters();
            cspParams.ProviderType = 1; // PROV_RSA_FULL 
            //cspParams.ProviderName; // CSP name
            rsaProvider = new RSACryptoServiceProvider(cspParams);

            // Read private/public key pair from file
            privateKeyFile = File.OpenText(privateKeyFileName);
            privateKeyText = privateKeyFile.ReadToEnd();

            // Import private/public key pair
            rsaProvider.FromXmlString(privateKeyText);

            // Read encrypted text from file
            encryptedFile = File.OpenRead(encryptedFileName);
            encryptedBytes = new byte[encryptedFile.Length];
            encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length);

            // Decrypt text
            plainBytes = rsaProvider.Decrypt(encryptedBytes, false);

            // Write decrypted text to file
            plainFile = File.CreateText(plainFileName);
            plainText = Encoding.Unicode.GetString(plainBytes);
            plainFile.Write(plainText);
        }
        catch (Exception ex)
        {
            // Any errors? Show them
            Console.WriteLine("Exception decrypting file! More info:");
            Console.WriteLine(ex.Message);
        }
        finally
        {
            // Do some clean up if needed
            if (privateKeyFile != null)
            {
                privateKeyFile.Close();
            }
            if (encryptedFile != null)
            {
                encryptedFile.Close();
            }
            if (plainFile != null)
            {
                plainFile.Close();
            }
        }

    } // Decrypt

共有1个答案

曹焱
2023-03-14

这是我想出来的。基本上,使用BouncyCastle和C#读取私有openssl密钥如下所示:

static AsymmetricKeyParameter readPrivateKey(string privateKeyFileName)
{
    AsymmetricCipherKeyPair keyPair;

    using (var reader = File.OpenText(privateKeyFileName))
        keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();

    return keyPair.Private;
}

那么这个密钥就可以用来解密下面这样的数据:

AsymmetricKeyParameter key = readPrivateKey(pemFilename);       
RsaEngine e = new RsaEngine();      
e.Init(false, key);

byte[] decipheredBytes = e.ProcessBlock(cipheredData, 0, cipheredData.Length);
 类似资料:
  • 以前有人这么做过吗?谢谢

  • 问题内容: 我试图将密码安全地存储在数据库中,为此,我选择存储使用PBKDF2函数生成的哈希值。我想使用弹性城堡库来执行此操作,但是我不知道为什么我无法通过使用JCE接口来使其工作…问题是,以三种不同的方式生成哈希值: 1.使用PBKDF2WithHmacSHA1秘密密钥由sun提供的工厂 。2.直接 使用有弹性的城堡api。3.通过JCE使用有弹性的城堡会 产生2个不同的值:前两个值相同,第三个

  • 我一直在尝试使用BouncyCastle库来进行PGP加密/解密。我有一些代码需要修改,以便只使用流-不使用文件。 我尝试移除pgputilities.writeFileToliteralData(),然后让它返回一个流,但没有成功(输出流为空)。 这里更明确的是方法应该是什么: 下面是我需要修改的代码:

  • 我目前正在将我的C#AES-GCM密码代码转换为PHP。然而,经过一些研究,我的PHP系统加密的文本不能被C#one解密。我想知道这两种代码是否有区别: C#带弹跳壳: 下面是PHP系统: 有没有人能告诉我,PHP代码中是否有遗漏或不同之处,导致它们的工作方式有所不同?或者PHP函数和BouncyCastle函数之间是否存在某种内部差异,从而使它们有所不同?

  • 我正在尝试使用BouncyCastle在运行mbedTLS和Java的嵌入式设备之间进行ECDH。当我比较生成的密钥长度时,我得到了由mbedTLS制作的66字节密钥和由BC制作的65字节密钥。附加伪代码: MbedTLS: 当我将MbedTLS密钥加载到Java中时,它会抛出java.lang.IllegalArgumentException:无效的点编码0x41: 我尝试在Java和MbedT