Closed simphonydeveloper closed 6 months ago
Hi, @simphonydeveloper Thanks for sharing your question.
you can not just Convert.ToBase64String(encrypt) and convert back to a string. It won't work how you think. I am not sure why you are doing this.
This will work
ICryptoNet cryptoNet = new CryptoNetRsa();
string PrivateKeyFile = Path.Combine(AppContext.BaseDirectory, "privateKey");
string PublicKeyFile = Path.Combine(AppContext.BaseDirectory, "publicKey.pub");
cryptoNet.ExportKeyAndSave(new FileInfo(PrivateKeyFile), true);
cryptoNet.ExportKeyAndSave(new FileInfo(PublicKeyFile), false);
ICryptoNet cryptoNetPubKey = new CryptoNetRsa(new FileInfo(key));
var encrypt = cryptoNetPubKey.EncryptFromString("1");
return encrypt;
ICryptoNet cryptoNetPriKey = new CryptoNetRsa(new FileInfo(key));
var decrypt = cryptoNetPriKey.DecryptToString(data);
return decrypt;
if you need to encrypt bytes and decrypt bytes you can do the following:
ICryptoNet cryptoNetPubKey = new CryptoNetRsa(new FileInfo(key));
var encrypt = cryptoNetPubKey.EncryptFromBytes("1");
return encrypt;
ICryptoNet cryptoNetPriKey = new CryptoNetRsa(new FileInfo(key));
var decrypt = cryptoNetPriKey.DecryptToBytes(data);
return decrypt;
However, if you need to do some base 64 conversion, you should encode that before the encryption process and after the decryption process. Here is an example:
for encryption part
var base64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("1"));
var encrypt = cryptoNetPubKey.EncryptFromString(base64);
for decryption part
var decrypt = cryptoNetPriKey.DecryptToString(data);
var output = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(decrypt));
Let me know 😃
@simphonydeveloper I am going to close this. Suppose it does solve your issue. If not create a new question.
thanks you.
Environment: win10 .NET VERSION: .NET6 Application: WebAPI
These my generate key method.
encrypt code
decrypt code