使用X509certificate2进行RSA加密和解密 [英] RSA Encryption and Decryption with X509certificate2

查看:236
本文介绍了使用X509certificate2进行RSA加密和解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我需要的是下一个:

  1. 创建用于开发的证书,为客户端获得一个证书,为服务器获得一个证书
  2. 通过从客户端编码的API检索密码,然后在服务器上对其进行解码

现在,我设法按照

现在,对于解密,我正在使用下一个代码:

 公共静态字符串DecryptEncryptedData(字符串Base64EncryptedData,字符串PathToPrivateKey){X509Certificate2 myCertificate;尝试{myCertificate =新的X509Certificate2(PathToPrivateKey,"Test123");}捕获(异常e){抛出新的CryptographicException(无法打开密钥文件.");}RSACryptoServiceProvider rsaObj;如果(myCertificate.HasPrivateKey){rsaObj =(RSACryptoServiceProvider)myCertificate.PrivateKey;}别的抛出新的CryptographicException(证书中不包含私有密钥.");如果(rsaObj == null)返回String.Empty;byte [] unlockedBytes;尝试{unlockedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData),false);}捕获(异常e){抛出新的CryptographicException(无法解密数据.");}//检查以确保我们删除了字符串如果(decryptedBytes.Length == 0)返回String.Empty;别的返回System.Text.Encoding.UTF8.GetString(decryptedBytes);} 

无论我做什么,都会给我例外:

  {输入不是有效的Base-64字符串,因为它包含非Base 64字符,两个以上的填充字符或填充字符中的非法字符."} 

真的很感谢有人帮助我.

解决方案

这不是您可能期望的确切答案,但是我在这里写是因为它太长了,不能发表评论.

我认为解密本身根本没有问题(我已经找到了使用php加密的代码示例博客),这就是为什么我说我对作为解密目标的加密字符串感到好奇.

几个月来我在理解安全性方面也很努力,现在我同时使用了对称(AES)和不对称(RSA).理解真的很重要,每个人都需要时间..

RSA是非对称且单向的,这意味着只能通过公用密钥来进行加密,而只能通过私钥来进行解密.您在加密"方法中使用私钥,它似乎只是从解密"中复制的.

Zesty的答案仅在格式方面是正确的.您还需要了解格式.从字节到base64string的加密和解密中,我们需要Convert.ToBase64String和Convert.FromBase64String,反之亦然.但是,此base64string不仅像'hello'一样简单,而且如您在此处

I've managed to encrypt my data using this code:

public static string Encrypt(string stringForEncription, string PathToPrivateKey)
    {
        X509Certificate2 myCertificate;
        try
        {
            myCertificate = new X509Certificate2(PathToPrivateKey, "Test123");
        }
        catch (Exception e)
        {
            throw new CryptographicException("Unable to open key file.");
        }

        RSACryptoServiceProvider rsaObj;
        if (myCertificate.HasPrivateKey)
        {
            rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
        }
        else
            throw new CryptographicException("Private key not contained within certificate.");

        if (rsaObj == null)
            return String.Empty;

        byte[] decryptedBytes;
        byte[] array = Encoding.UTF8.GetBytes(stringForEncription);
        try
        {
            decryptedBytes = rsaObj.Encrypt(array, false);
            //decryptedBytes = rsaObj.Encrypt(Convert.FromBase64String(Base64EncryptedData), false);
        }
        catch (Exception e)
        {
            throw new CryptographicException("Unable to encrypt data.");
        }

        //    Check to make sure we decrpyted the string 
        if (decryptedBytes.Length == 0)
            return String.Empty;
        else
            return System.Text.Encoding.UTF8.GetString(decryptedBytes);
    }

For PathToPrivate key variable I am using the path to my client ClientCert.pfx. I don't know if I should use any other, but here is the snap of the folder with all the certificates that I made:

Now, for the decryption, I'm using next code:

 public static string DecryptEncryptedData(string Base64EncryptedData, string PathToPrivateKey)
    {
        X509Certificate2 myCertificate;
        try
        {
            myCertificate = new X509Certificate2(PathToPrivateKey, "Test123");
        }
        catch (Exception e)
        {
            throw new CryptographicException("Unable to open key file.");
        }

        RSACryptoServiceProvider rsaObj;
        if (myCertificate.HasPrivateKey)
        {
            rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
        }
        else
            throw new CryptographicException("Private key not contained within certificate.");

        if (rsaObj == null)
            return String.Empty;

        byte[] decryptedBytes;
        try
        {
            decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false);
        }
        catch (Exception e)
        {
            throw new CryptographicException("Unable to decrypt data.");
        }

        //    Check to make sure we decrpyted the string 
        if (decryptedBytes.Length == 0)
            return String.Empty;
        else
            return System.Text.Encoding.UTF8.GetString(decryptedBytes);
    }

And whatever I try to do, it gives me exception:

{"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "}

Would really apreciate somebody helping me out.

解决方案

This is not the exact answer which you might expected but I write here as it's too long as a comment.

I think the decryption itself has no problem at all (I've found the example blog of your code with php encryption) That's why I commented I was curious on the encryptedstring which is the target of decryption.

I also struggled in understanding Security for months and now I use symmetric(AES) and asymmetric(RSA) together. Understanding is really important and everybody takes time..

RSA is asymmetric and one-way which means the Encryption can be done only by public key and the Decryption can be done only by private key. You're using private key in Encryption method and it seems just copied from Decryption.

The answer by Zesty is right only in terms of formatting. You're also needed to understand the formatting. We need Convert.ToBase64String and Convert.FromBase64String in Encryption and Decryption from byte to base64string and vice versa. However this base64string is not just plain like 'hello' but 'SABlAGwAbABvACAAVwBvAHIAbABkAA==' as you see here

And I kindly recommend to use complete solution(not half one like php encryption) like this blog so that Encryption and Decryption and all are in harmony.

And as last as I commented also, you're needed to think about how to prevent the black users if encryption is done from client side and you don't have only good users.

I hope my experience helps to understand Security which is of most importance.

这篇关于使用X509certificate2进行RSA加密和解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆