简体   繁体   中英

How to pass CspParameters to another RSACryptoServiceProvider to encryption and Decrypt it

I'm currently working on a project with Xamarin and WCF, in which WCF will generate CspParameter at WCF and pass the Blob to Xamarin.

CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = KEY_CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseArchivableKey | CspProviderFlags.NoPrompt | CspProviderFlags.UseMachineKeyStore;

RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(KEY_SIZE_BIT, cspParams) { PersistKeyInCsp = true };

In which later on the WCF return the byte[] of the CspBlob using the code below.

rsaProvider.ExportCspBlob(false)

At the client side (Xamarin app), I recreate the CspParameter and encrypt the text using the code below and send back to WCF function to decrypt.

RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
rsaProvider.ImportCspBlob(cspBlob);

string cipherText = rsaProvider.Encrypt(Encoding.UTF8.GetBytes(message), true);

Up until this point, there is not error. However, during the Decryption, there is an error.

CspParameters cspParams = new CspParameters() { KeyContainerName = KEY_CONTAINER_NAME };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);

byte[] decryptBytes = rsaProvider.Decrypt(cipherBytes, true); //Error here

The error is "Error occurred while decoding OAEP padding.". I search online, this error is due to invalid message upon decryption.

I have tested another flow which use the same CspParameter (without going thru the WCF and do everything within the same flow) to encrypt and decrypt, there is no error thrown. So I suspect it's because of the ExportCspBlob, in which the ImportCspBlob is not created as the same as the original CspParameter.

May I know if anybody got any suggestion on the workaround? Thanks.

Please Change from

string cipherText = rsaProvider.Encrypt(Encoding.UTF8.GetBytes(message), true);

to

byte[] cipherText = rsaProvider.Encrypt(Encoding.UTF8.GetBytes(message), true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM