CryptographicBuffer.ConvertBinaryToString causes unicode exception on W10 universal app.

Maybe someone could shine some light on my problem. I am trying to decode a string but it causes an exception.

I am trying to follow these specs

  • First, base64 decode the encrypted url

  • Then take the first 16 bytes of the decoded url as $IV and the rest as $MESSAGE

  • Create a cipher with AES/CBC/PKCS7Padding (AES/CBC/PKCS5Padding in JVM based languages)

  • Initialize the cipher in decrypt mode with your $SECRET and $IV

  • Decrypt the $MESSAGE using the cipher

and I also got some java example

import javax.crypto.Cipher; import javax.crypto.spec.*; import java.util.Base64; import java.util.Arrays; public class Decrypt { public static void main(String args[]) throws Exception { String secret = "this_is_your_secret"; String data = "this_is_the_url"; Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] baseDecoded = Base64.getDecoder().decode(data); byte[] iv = Arrays.copyOfRange(baseDecoded, 0, 16); byte[] msg = Arrays.copyOfRange(baseDecoded, 16, baseDecoded.length); SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec); byte[] resultBytes = cipher.doFinal(msg); System.out.println(new String(resultBytes)); } } 

Here is my code

 private string DecryptUrl(string strBase64) { // Convert the properties to required buffers var buffer = CryptographicBuffer.DecodeFromBase64String(strBase64); //this is something ugly... var iv = buffer.ToArray().Take(16).ToArray(); var message = buffer.ToArray().Skip(16).ToArray().ToString(); var pwBuffer = CryptographicBuffer.ConvertStringToBinary(secret, BinaryStringEncoding.Utf8); var saltBuffer = CryptographicBuffer.CreateFromByteArray(iv); //var buffer = CryptographicBuffer.DecodeFromBase64String(strBase64); // Load the alghorithm providers var symmetricKeyProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // Create the symmetric key that is used to encrypt the string from IV var cryptoKey = symmetricKeyProvider.CreateSymmetricKey(pwBuffer); // Decrypt the IBuffer back to byte array var resultBuffer = CryptographicEngine.Decrypt(cryptoKey, buffer, saltBuffer); // Get string back from the byte array try { var hex = CryptographicBuffer.EncodeToHexString(resultBuffer); var decryptedString = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, resultBuffer); return decryptedString; } catch (Exception ex) { throw; } } 

I think my code should do what is supposed to be done. Not that familiar with decrypting, but still can't understand why does this line CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, resultBuffer); throw this error

No mapping for the Unicode character exists in the target multi-byte code page. (Exception from HRESULT: 0x80070459)

by Virallinen via /r/csharp

Leave a Reply