/// <summary> /// Decrypt a string using dual encryption method. Return a Decrypted clear string /// </summary> /// <param name="cipherString">Encrypted string</param> /// <param name="key">Unique key for encryption/decryption</param> /// <returns>Returns decrypted text.</returns> public static string DecryptString(string cipherString, string key) { try { // Get the MD5 key hash (you can as well use the binary of the key string) var keyHash = GetMD5HashKey(key); // Create a buffer that contains the encoded message to be decrypted. IBuffer toDecryptBuffer = CryptographicBuffer.DecodeFromBase64String(cipherString); // Open a symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); // Create a symmetric key. var symetricKey = aes.CreateSymmetricKey(keyHash); var buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null); string strDecrypted = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecrypted); return(strDecrypted); } catch (Exception ex) { // MetroEventSource.Log.Error(ex.Message); //throw; return(""); } }
private async void Button_Click_6(object sender, RoutedEventArgs e) { string message = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, localBuffer); MessageDialog md = new MessageDialog(message); await md.ShowAsync(); }
public static async Task <string> decryptData(string str) { DataProtectionProvider Provider = new DataProtectionProvider("LOCAL=user"); IBuffer decryptedBuffer = await Provider.UnprotectAsync(CryptographicBuffer.DecodeFromBase64String(str)); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuffer)); }
/// <summary> /// The decrypt asymmetric. /// </summary> /// <param name="message"> /// The message. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> private string DecryptAsymmetric(string message) { IBuffer messageData = CryptographicBuffer.DecodeFromBase64String(message); var decryptedMessage = CryptographicEngine.Decrypt(this.keyPair, messageData, null); return(CryptographicBuffer.ConvertBinaryToString(Encoding, decryptedMessage)); }
public void AuthenticatedDecryptionSender( String strAlgName, string key, string message, string nonce, string tag) { // Open a SymmetricKeyAlgorithmProvider object for the specified algorithm. SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); IBuffer encryptedAESKey = CryptographicBuffer.DecodeFromBase64String(key); asymmetricDecryptAESKeySender(strAsymmetricAlgName, encryptedAESKey); IBuffer decryptedAESKeyBuff = CryptographicBuffer.DecodeFromBase64String(keyMaterialStringSender); CryptographicKey keyFromEncryptedString = objAlgProv.CreateSymmetricKey(decryptedAESKeyBuff); IBuffer encryptedDataFromStringBuff = CryptographicBuffer.DecodeFromBase64String(message); IBuffer nonceFromString = CryptographicBuffer.DecodeFromBase64String(nonce); IBuffer authenticationTagFromString = CryptographicBuffer.DecodeFromBase64String(tag); // The input key must be securely shared between the sender of the encrypted message // and the recipient. The nonce must also be shared but does not need to be shared // in a secure manner. If the sender encodes the message string to a buffer, the // binary encoding method must also be shared with the recipient. // The recipient uses the DecryptAndAuthenticate() method as follows to decrypt the // message, authenticate it, and verify that it has not been altered in transit. buffDecrypted = CryptographicEngine.DecryptAndAuthenticate( keyFromEncryptedString, encryptedDataFromStringBuff, nonceFromString, authenticationTagFromString, null); strDecrypted = CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted); }
public IAsyncOperation <IInputStream> UriToStreamAsync(System.Uri uri) { string path = uri.AbsolutePath; if (path.StartsWith("/ajax", StringComparison.OrdinalIgnoreCase)) { return(GetObject(new { a = 1, b = "b" }).AsAsyncOperation()); } string host = uri.Host; int delimiter = host.LastIndexOf('_'); string encodedContentId = host.Substring(delimiter + 1); IBuffer buffer = CryptographicBuffer.DecodeFromHexString(encodedContentId); string contentIdentifier = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer); string relativePath = uri.PathAndQuery; // For this sample, we will return a stream for a file under the local app data // folder, under the subfolder named after the contentIdentifier and having the // given relativePath. Real apps can have more complex behavior, such as handling // contentIdentifiers in a custom manner (not necessarily as paths), and generating // arbitrary streams that are not read directly from a file. System.Uri appDataUri = new Uri("ms-appx:///app" + relativePath); return(GetFileStreamFromApplicationUriAsync(appDataUri).AsAsyncOperation()); }
private static string Decrypt(String strMsg) { Byte[] bb = Convert.FromBase64String(strMsg); IBuffer buffEncrypt = CryptographicEngine.Decrypt(Key, bb.AsBuffer(), IV.AsBuffer()); return(CryptographicBuffer.ConvertBinaryToString(encoding, buffEncrypt)); }
public static string CipherDecryption( string strAlgName, IBuffer buffEncrypt, IBuffer iv, BinaryStringEncoding encoding, CryptographicKey key) { // Declare a buffer to contain the decrypted data. IBuffer buffDecrypted; // Open an symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // The input key must be securely shared between the sender of the encrypted message // and the recipient. The initialization vector must also be shared but does not // need to be shared in a secure manner. If the sender encodes a message string // to a buffer, the binary encoding method must also be shared with the recipient. buffDecrypted = CryptographicEngine.Decrypt(key, buffEncrypt, iv); // Convert the decrypted buffer to a string (for display). If the sender created the // original message buffer from a string, the sender must tell the recipient what // BinaryStringEncoding value was used. Here, BinaryStringEncoding.Utf8 is used to // convert the message to a buffer before encryption and to convert the decrypted // buffer back to the original plaintext. return(CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted)); }
private string DecryptInternal(string base64EncryptedData, CryptographicKey cryptographicKey, IBuffer iv) { IBuffer encryptedBinaryData = CryptographicBuffer.DecodeFromBase64String(base64EncryptedData); IBuffer decryptedData = CryptographicEngine.Decrypt(cryptographicKey, encryptedBinaryData, iv); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedData)); }
/// <summary> /// Used internally to handle the decryption /// </summary> /// <param name="buffEncrypt"></param> /// <returns></returns> private string CipherDecryption(IBuffer buffEncrypt) { IBuffer buffDecrypted; buffDecrypted = CryptographicEngine.Decrypt(key, buffEncrypt, iv); return(CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted)); }
public static async Task <String> GetPasswords(CryptographicKey AesKey) { CryptographicKey k = await GetRasKey(AesKey); String R = ""; try { int a = int.Parse(await StorageInterface.ReadFromRoamingFolder("PWM/INDEX")); for (int i = 0; i < a; i++) { IBuffer crypitic = await StorageInterface.ReadBufferFromRoamingFolder("PWM/Passwords" + i); IBuffer plain = DecryptRsa(k, crypitic); String X = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, plain); if (X == null) { X = ""; } R += X; } } catch (Exception e) { e.PrintStackTrace(); return(""); } return(R); }
private async void ProtectedAccessResumed(object sender, ProtectedAccessResumedEventArgs args) { string logFileContent = ""; // Keys are available so can read and write from a protected file m_areKeysDropped = false; // BufferProtectUnprotectResult unBuffer = await DataProtectionManager.UnprotectAsync(m_protectedBuffer); m_SecretMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, m_protectedBuffer ); logFileContent += "\n Unprotected string:" + m_SecretMessage; var settings = ApplicationData.Current.LocalSettings; settings.Values[m_taskName] += "\nApp got DPL resumed event"; StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile logFile = await localFolder.CreateFileAsync("ResumeLog.txt", CreationCollisionOption.OpenIfExists); await FileIO.AppendTextAsync(logFile, "\r\n" + DateTime.Now + ":" + "Got DPL Protected resumed"); }
public static string Decrypt(string cipherString, byte[] key = null) { if (cipherString == "") { return(""); } if (key == null || key.Length == 0) { key = Default; } var keyHash = key.AsBuffer(); // Create a buffer that contains the encoded message to be decrypted. IBuffer toDecryptBuffer = CryptographicBuffer.DecodeFromBase64String(cipherString); // Open a symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesEcbPkcs7); // Create a symmetric key. var symetricKey = aes.CreateSymmetricKey(keyHash); var buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null); string strDecrypted = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecrypted); return(strDecrypted); }
public static async Task <string> UnprotectData(IBuffer buffProtected) { var buffUnprotected = await new DataProtectionProvider().UnprotectAsync(buffProtected); var strClearText = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUnprotected); return(strClearText); }
private async Task <TEntity> GetAsync <TEntity>(string name, bool secure) { try { if (secure) { var s = await SecureStorage.GetAsync(name); return((string.IsNullOrEmpty(s)) ? default(TEntity) : Serializer.Deserialize <TEntity>(s)); } else { if (!Exists(name)) { return(default(TEntity)); } var file = await ApplicationData.Current.LocalFolder.GetFileAsync(name); var buffer = await FileIO.ReadBufferAsync(file); var json = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer); return(Serializer.Deserialize <TEntity>(json)); } } catch (FileNotFoundException fex) { System.Diagnostics.Debug.WriteLine(string.Format("*** LocalStorageManager.GetAsync - File Not Found: {0}", name)); return(default(TEntity)); } }
public async Task <string> UnprotectStringAsync(string protectedString) { var provider = this.GetDataProtectionProvider(); IBuffer buffUnprotectedData; using (InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream()) using (InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream()) { IOutputStream outputStream = inputData.GetOutputStreamAt(0); using (DataWriter writer = new DataWriter(outputStream)) { writer.WriteBuffer(Convert.FromBase64String(protectedString).AsBuffer()); await writer.StoreAsync(); await outputStream.FlushAsync(); } IInputStream source = inputData.GetInputStreamAt(0); IOutputStream dest = unprotectedData.GetOutputStreamAt(0); await provider.UnprotectStreamAsync(source, dest); await dest.FlushAsync(); using (DataReader reader = new DataReader(unprotectedData.GetInputStreamAt(0))) { await reader.LoadAsync((uint)unprotectedData.Size); buffUnprotectedData = reader.ReadBuffer((uint)unprotectedData.Size); } } return(CryptographicBuffer.ConvertBinaryToString(Encoding, buffUnprotectedData)); }
/// <summary> /// Aes解密函数 /// </summary> /// <param name="str">密文</param> /// <param name="key">密钥</param> /// <returns>解密结果</returns> public static string DecryptString(string str, string key) { if (string.IsNullOrEmpty(str)) { return(null); } if (string.IsNullOrEmpty(key)) { return(null); } if (key.Length != 32) { return(null); } try { SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); IBuffer buffDecrypt = CryptographicBuffer.DecodeFromBase64String(str); IBuffer buffKey = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); CryptographicKey cKey = provider.CreateSymmetricKey(buffKey); IBuffer buffResult = CryptographicEngine.Decrypt(cKey, buffDecrypt, null); string strResult = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffResult); return(strResult); } catch (Exception) { return(null); } }
private async void DoBufferWork(IBackgroundTaskInstance taskInstance) { string message = "Hello World!"; string unprotectedMessage = ""; string logFileName = "Bufferlog.txt"; string logFileContent = ""; StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile logFile = await localFolder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists); IBuffer inputBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8); BufferProtectUnprotectResult procBuffer = await DataProtectionManager.ProtectAsync(inputBuffer, m_EnterpriseID); logFileContent += "\r\n" + DateTime.Now + ":" + "ProtStatus:" + procBuffer.ProtectionInfo.Status + "\n"; logFileContent += "\r\n" + "Protected Buffer:" + CryptographicBuffer.EncodeToHexString(procBuffer.Buffer).Substring(0, 5); // If keys are dropped under lock, unprotectBuffer will fail so don't unprotectbuffer under lock if (!m_areKeysDropped) { BufferProtectUnprotectResult unBuffer = await DataProtectionManager.UnprotectAsync(procBuffer.Buffer); unprotectedMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, procBuffer.Buffer); logFileContent += "\n Unprotected string:" + unprotectedMessage; if (message != unprotectedMessage) { throw new Exception("Original string does not match with unprotectedMessage!"); } } await FileIO.AppendTextAsync(logFile, logFileContent); }
/*** * This function decrypts the encrypted text to plain text using the key * provided. You'll have to use the same key which you used during * encryption * * @param _encryptedText * Encrypted/Cipher text to be decrypted * @param _key * Encryption key which you used during encryption */ private string encryptDecrypt(string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector) { SymmetricKeyAlgorithmProvider aesCbcPkcs7 = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // Creata a 16 byte initialization vector IBuffer iv = CryptographicBuffer.ConvertStringToBinary(_initVector, BinaryStringEncoding.Utf8); // Create an AES 128-bit (16 byte) key IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(_encryptionKey, BinaryStringEncoding.Utf8); CryptographicKey key = aesCbcPkcs7.CreateSymmetricKey(keyMaterial); if (_mode.Equals(EncryptMode.ENCRYPT)) { // Encrypt the data IBuffer plainText = CryptographicBuffer.ConvertStringToBinary(_inputText, BinaryStringEncoding.Utf8); IBuffer cipherText = CryptographicEngine.Encrypt(key, plainText, iv); string strEncrypted64 = CryptographicBuffer.EncodeToBase64String(cipherText); return(strEncrypted64); } else { // Decrypt the data IBuffer cipherText = CryptographicBuffer.DecodeFromBase64String(_inputText); IBuffer decryptedText = CryptographicEngine.Decrypt(key, cipherText, iv); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedText)); } }
private async void UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e) { string outputStr = ""; string plainMessage = ""; try { if (m_protectedBuffer != null) { BufferProtectUnprotectResult unBuffer = await DataProtectionManager.UnprotectAsync(m_protectedBuffer); m_unprotectedBuffer = unBuffer.Buffer; plainMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, m_unprotectedBuffer ); outputStr += "\n Status: " + unBuffer.ProtectionInfo.Status; outputStr += "\n Unprotected string:" + plainMessage; rootPage.NotifyUser(outputStr, NotifyType.StatusMessage); } else { rootPage.NotifyUser("Please protect a buffer to unprotect", NotifyType.ErrorMessage); } } catch (Exception ex) { rootPage.NotifyUser(outputStr + "\n" + ex.ToString(), NotifyType.ErrorMessage); } }
/// <summary> /// Decrypts the specified data using a 256-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be decrypted.</param> /// <param name="Key">The key used to decrypt the data.</param> /// <returns>A string containing the decoded data.</returns> public static string Decrypt256String(byte[] Data, byte[] Key) { KeyData KeyData = GenerateKeyIV256(Key); SymmetricKeyAlgorithmProvider AES = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, CryptographicEngine.Decrypt(AES.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(KeyData.Key)), CryptographicBuffer.CreateFromByteArray(Data), CryptographicBuffer.CreateFromByteArray(KeyData.IV)))); }
private string AesDecrypt(string encryptionKey, string value) { if (string.IsNullOrEmpty(value)) { return(value); } IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(encryptionKey, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(passwordBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(passwordBuffer); IBuffer ivBuffer = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); CryptographicKey aesKey = aes.CreateSymmetricKey(keyMaterial); IBuffer decryptedContentBuffer = CryptographicEngine.Decrypt(aesKey, CryptographicBuffer.DecodeFromBase64String(value), ivBuffer); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedContentBuffer)); }
//Decrypts Data (Always using private key) public static string Decrypt(String strAsymmetricAlgName, IBuffer buffPrivateKeyStorage, string encryptedMessage) { // Open the algorithm provider for the specified asymmetric algorithm. AsymmetricKeyAlgorithmProvider objAsymmAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName); // Import the public key from a buffer. You should keep your private key // secure. For the purposes of this example, however, the private key is // just stored in a static class variable. CryptographicKey keyPair = objAsymmAlgProv.ImportKeyPair(buffPrivateKeyStorage); //Convert message String to IBuffer IBuffer convertedString = CryptographicBuffer.DecodeFromBase64String(encryptedMessage); IBuffer buffDecryptedMessage; try { // Use the private key embedded in the key pair to decrypt the session key. buffDecryptedMessage = CryptographicEngine.Decrypt(keyPair, convertedString, null); } catch (System.ArgumentException) { string invalidDecryptionMessage = "INVALID DECRYPTION KEY"; return(invalidDecryptionMessage); } //Return decrpyted message as a string string decryptedMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecryptedMessage); return(decryptedMessage); }
public static string GetDataLabelString(IBuffer data, uint scanDataType) { // Only certain data types contain encoded text. // To keep this simple, we'll just decode a few of them. if (data == null) { return("No data"); } // This is not an exhaustive list of symbologies that can be converted to a string. if (scanDataType == BarcodeSymbologies.Upca || scanDataType == BarcodeSymbologies.UpcaAdd2 || scanDataType == BarcodeSymbologies.UpcaAdd5 || scanDataType == BarcodeSymbologies.Upce || scanDataType == BarcodeSymbologies.UpceAdd2 || scanDataType == BarcodeSymbologies.UpceAdd5 || scanDataType == BarcodeSymbologies.Ean8 || scanDataType == BarcodeSymbologies.TfStd) { // The UPC, EAN8, and 2 of 5 families encode the digits 0..9 // which are then sent to the app in a UTF8 string (like "01234"). return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, data)); } // Some other symbologies (typically 2-D symbologies) contain binary data that // should not be converted to text. return(string.Format("Decoded data unavailable. Raw label data: {0}", DataHelpers.GetDataString(data))); }
/// <inheritdoc /> public async Task <IEnumerable <string> > GetStringsForIdentifier(string identifier) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { // Create a DataProtectionProvider object. var provider = new DataProtectionProvider(Descriptor); var returnList = new List <string>(); foreach (var path in store.GetFileNames(GetStringsPath(identifier))) { using (var stream = new BinaryReader(new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, store))) { var length = stream.ReadInt32(); var dataAsBytes = stream.ReadBytes(length); // Decrypt the protected message specified on input. var buffUnprotected = await provider.UnprotectAsync(dataAsBytes.AsBuffer()); // Execution of the SampleUnprotectData method resumes here // after the awaited task (Provider.UnprotectAsync) completes // Convert the unprotected message from an IBuffer object to a string. returnList.Add(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUnprotected)); } } return(returnList); } }
public static string AesDecrypt(this byte[] encrypted, string password, string salt) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encrypted); // Derive key material for password size 32 bytes for AES256 algorithm KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); // using salt and 1000 iterations KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); // create a key based on original key and derivation parmaters CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption salt from derived password key IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); // display the keys – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); // create symmetric key from derived password material CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); // encrypt data buffer using symmetric key and derived salt material IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); return(result); }
public static string WinRTEncrypt(string publicKey, string data) { string strIn = "Input String"; IBuffer buffUTF8 = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8); String strUTF8 = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUTF8); IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey); AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); //AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha256); CryptographicKey key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey); IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8); IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null); //string result = CryptographicBuffer.EncodeToHexString(encryptedBuffer); //string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, encryptedBuffer); string result = CryptographicBuffer.EncodeToBase64String(encryptedBuffer); return(result); }
/// <summary> /// Get the current value of the setting, or if it is not found, set the /// setting to the default setting. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public async static Task <string> GetEncryptedLocalStringValueOrDefault(string Key, string defaultValue) { string value; // If the key exists, retrieve the value. var obj = ApplicationData.Current.LocalSettings.Values[Key]; if (obj != null) { value = (string)ApplicationData.Current.LocalSettings.Values[Key]; if (value != null) { IBuffer EncryptedBytes = Convert.FromBase64String(value).AsBuffer(); var provider = new DataProtectionProvider(); IBuffer UnencryptedBytes = await provider.UnprotectAsync(EncryptedBytes); string Final_UnEncryptedString = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, UnencryptedBytes); return(Final_UnEncryptedString); } } // Otherwise, use the default value. else { value = defaultValue; } return(value); }
/// <summary> /// Decrypt a string previously ecnrypted with Encrypt method and the same password /// </summary> /// <param name="input">String to decrypt</param> /// <param name="password">Password to use for decryption</param> /// <returns>Decrypted string</returns> public static string DecryptToString(IBuffer ibuf) { // get IV, key and decrypt var iv = CryptographicBuffer.CreateFromByteArray(UTF8Encoding.UTF8.GetBytes(EncryptionProvider.PublicKey)); SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc); var buffer = CryptographicBuffer.ConvertStringToBinary(EncryptionProvider.PublicKey, BinaryStringEncoding.Utf8); var key = provider.CreateSymmetricKey(buffer); //IBuffer binput = CryptographicBuffer.DecodeFromBase64String(input); IBuffer decryptedBuffer = CryptographicEngine.Decrypt(key, ibuf, iv); byte[] b; CryptographicBuffer.CopyToByteArray(decryptedBuffer, out b); char[] ch = System.Text.Encoding.UTF8.GetChars(b); StringBuilder sb = new StringBuilder(); foreach (char c in ch) { if (c == '\0') { break; } sb.Append(c); } string s = sb.ToString(); try { return((CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuffer)).TrimEnd(new char[] { '\0' })); } catch (Exception ex) { return(s); } }
private async Task <string> DecryptAsync(byte[] protectedBytes) { DataProtectionProvider provider = new DataProtectionProvider("LOCAL=user"); var protectedBuffer = CryptographicBuffer.CreateFromByteArray(protectedBytes); var plainBuffer = await provider.UnprotectAsync(protectedBuffer); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, plainBuffer)); }