public static string GetMd5String(string result) { //可以选择MD5 Sha1 Sha256 Sha384 Sha512 string strAlgName = HashAlgorithmNames.Md5; // 创建一个 HashAlgorithmProvider 对象 HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName); // 创建一个可重用的CryptographicHash对象 CryptographicHash objHash = objAlgProv.CreateHash(); IBuffer buffMsg1 = CryptographicBuffer.ConvertStringToBinary(result, BinaryStringEncoding.Utf16BE); objHash.Append(buffMsg1); IBuffer buffHash1 = objHash.GetValueAndReset(); string strHash1 = CryptographicBuffer.EncodeToHexString(buffHash1); return(strHash1); }
public string EncryptString(string data, bool reuseGlobalIV = false) { Arguments.NotNull(data, nameof(data)); if (string.IsNullOrEmpty(data)) { return(data); } CryptographicKey cryptographicKey; IBuffer iv; lock (_lock) { if (_cryptographicKey == null) { throw new InvalidOperationException($"No encryption key found. Invoke '{nameof(LoadSecretKeysFromPasswordVault)}' or '{nameof(SetSecretKeys)}' first."); } cryptographicKey = _cryptographicKey; if (reuseGlobalIV) { iv = _aesGlobalIV; } else { iv = CryptographicBuffer.GenerateRandom(IVLength); } } var binaryData = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8); IBuffer encryptedBinaryData = CryptographicEngine.Encrypt(cryptographicKey, binaryData, iv); string encryptedStringData = CryptographicBuffer.EncodeToBase64String(encryptedBinaryData); if (!reuseGlobalIV) { encryptedStringData = CryptographicBuffer.EncodeToBase64String(iv) + IVSeparator + encryptedStringData; } return(encryptedStringData); }
private static string ToSha1(string contents) { IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(contents, BinaryStringEncoding.Utf8); // Grab the algoritm HashAlgorithmProvider algorithm = HashAlgorithmProvider.OpenAlgorithm("SHA1"); // Hash the data IBuffer buffHash = algorithm.HashData(buffer); // Verify that hash succeeded if (buffHash.Length != algorithm.HashLength) { throw new Exception("There was an error creating the hash."); } // Convert to string return(CryptographicBuffer.EncodeToHexString(buffHash)); }
public static void RegisterWithShell() { try { var info = new StorageProviderSyncRootInfo(); info.Id = GetSyncRootId(); var folder = StorageFolder.GetFolderFromPathAsync(ProviderFolderLocations.ClientFolder).GetResults(); info.Path = folder; info.DisplayNameResource = "TestStorageProviderDisplayName"; info.IconResource = "%SystemRoot%\\system32\\charmap.exe,0"; // This icon is just for the sample. You should provide your own branded icon here info.HydrationPolicy = StorageProviderHydrationPolicy.Full; info.HydrationPolicyModifier = StorageProviderHydrationPolicyModifier.None; info.PopulationPolicy = StorageProviderPopulationPolicy.AlwaysFull; info.InSyncPolicy = StorageProviderInSyncPolicy.FileCreationTime | StorageProviderInSyncPolicy.DirectoryCreationTime; info.Version = "1.0.0"; info.ShowSiblingsAsGroup = false; info.HardlinkPolicy = StorageProviderHardlinkPolicy.None; info.RecycleBinUri = new Uri("http://cloudmirror.example.com/recyclebin"); var syncRootIdentity = ProviderFolderLocations.ServerFolder + "->" + ProviderFolderLocations.ClientFolder; info.Context = CryptographicBuffer.ConvertStringToBinary(syncRootIdentity, BinaryStringEncoding.Utf8); AddCustomState("CustomStateName1", 1); AddCustomState("CustomStateName2", 2); AddCustomState("CustomStateName3", 3); StorageProviderSyncRootManager.Register(info); // Give the cache some time to invalidate Sleep(1000); void AddCustomState(string displayNameResource, int id) => info.StorageProviderItemPropertyDefinitions.Add(new StorageProviderItemPropertyDefinition { DisplayNameResource = displayNameResource, Id = id }); } catch (Exception ex) { // to_hresult() will eat the exception if it is a result of check_hresult, otherwise the exception will get rethrown and // this method will crash out as it should Console.Write("Could not register the sync root, hr {0:X8}\n", ex.HResult); throw; } }
/// <summary> /// 计算MD5哈希(可能需要关闭FIPS) /// </summary> /// <param name="str">待计算的字符串</param> /// <returns>MD5结果</returns> public static string CalcMD5(string str) { #if WINDOWS_UWP var md5 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); var buf = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8); var digest = md5.HashData(buf); return(CryptographicBuffer.EncodeToHexString(digest)); #else MD5 md5 = MD5.Create(); byte[] data = Encoding.UTF8.GetBytes(str); byte[] hashData = md5.ComputeHash(data); StringBuilder sb = new StringBuilder(hashData.Length * 2); foreach (byte b in hashData) { sb.AppendFormat("{0:x2}", b); } return(sb.ToString()); #endif }
private static IBuffer GetMD5Hash(string key) { // Convert the message string to binary data. IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf16BE); // Create a HashAlgorithmProvider object. HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); // Hash the message. IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg); // Verify that the hash length equals the length specified for the algorithm. if (buffHash.Length != objAlgProv.HashLength) { throw new Exception("There was an error creating the hash"); } return(buffHash); }
public static string Encrypt(string text) { IBuffer keyMaterial; IBuffer iv; Settings.GenerateKey(out keyMaterial, out iv); IBuffer clearTextBuffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8); // Setup an AES key, using AES in CBC mode and applying PKCS#7 padding on the input SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(Settings.SymmetricAlgorithm); CryptographicKey key = provider.CreateSymmetricKey(keyMaterial); // Encrypt the data and convert it to a Base64 string IBuffer encrypted = CryptographicEngine.Encrypt(key, clearTextBuffer, iv); string ciphertextString = CryptographicBuffer.EncodeToBase64String(encrypted); return(ciphertextString); }
internal static string ComputeHmac256(byte[] key, string message) { #if RT MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA256"); IBuffer keyMaterial = CryptographicBuffer.CreateFromByteArray(key); CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(keyMaterial); IBuffer messageBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8); IBuffer signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer); return(CryptographicBuffer.EncodeToBase64String(signedMessage)); #elif COMMON return(null); #else using (HashAlgorithm hashAlgorithm = new HMACSHA256(key)) { byte[] messageBuffer = Encoding.UTF8.GetBytes(message); return(Convert.ToBase64String(hashAlgorithm.ComputeHash(messageBuffer))); } #endif }
private byte[] EncryptDataV2(byte[] bytes, string pw, string salt) { var base64Text = Convert.ToBase64String(bytes); var pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); var saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); var plainBuffer = CryptographicBuffer.ConvertStringToBinary(base64Text, BinaryStringEncoding.Utf16LE); // Derive key material for password size 32 bytes for AES256 algorithm var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); // using salt and 1000 iterations var pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); // create a key based on original key and derivation parmaters var keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); var derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); // derive buffer to be used for encryption salt from derived password key var saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); // display the buffers – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately //var keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); //var saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); var symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // create symmetric key from derived password key var symmKey = symProvider.CreateSymmetricKey(keyMaterial); // encrypt data buffer using symmetric key and derived salt material var resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial); byte[] result; CryptographicBuffer.CopyToByteArray(resultBuffer, out result); if (result.Length > 1000000) { GC.Collect(); } return(result); }
/// <summary> /// Obtiene los datos cifrados con DES /// </summary> /// <param name="data">Datos a cifrar</param> /// <param name="keyString">clave con la que cifrar</param> /// <returns></returns> public static byte[] getDES(byte[] data, string keyString) { //creamos el proveedor de cifrado SymmetricKeyAlgorithmProvider symmetricKeyAlgorithmProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.DesEcb); // Declaramos el encoding BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; // Creamos un buffer con el contenido de la clave IBuffer buffkey = CryptographicBuffer.ConvertStringToBinary(keyString, encoding); //creamos la clave CryptographicKey cryptographicKey = symmetricKeyAlgorithmProvider.CreateSymmetricKey(buffkey); // Creamos un buffer con el contenido a cifrar IBuffer dataBuffer = CryptographicBuffer.CreateFromByteArray(data); IBuffer dataToSign = dataBuffer; if ((data.Length % 8) > 0) { int diff = (int)(data.Length % 8); byte[] buff = new byte[dataBuffer.Length + (8 - diff)]; for (int i = 0; i < buff.Length; i++) { buff[i] = 0; } Array.Copy(data, buff, data.Length); dataToSign = CryptographicBuffer.CreateFromByteArray(buff); } //ciframos IBuffer cipherTextBuffered = CryptographicEngine.Encrypt(cryptographicKey, dataToSign, null); //Se prepara el contenedor del mensaje cifrado byte[] cipherText = new byte[cipherTextBuffered.Length]; //Se copia el contenido CryptographicBuffer.CopyToByteArray(cipherTextBuffered, out cipherText); //se devuelve el contenido cifrado. return(cipherText); }
public async void Load() { try { if (await KeyCredentialManager.IsSupportedAsync()) { var result = await KeyCredentialManager.OpenAsync(Helper.AppName); if (result.Credential != null) { var signResult = await result.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary(DeviceHelper.PackageName, BinaryStringEncoding.Utf8)); if (signResult.Status == KeyCredentialStatus.Success) { Unlock(); } else { BiometricsButton.Visibility = Visibility.Visible; } } else { var creationResult = await KeyCredentialManager.RequestCreateAsync(Helper.AppName, KeyCredentialCreationOption.ReplaceExisting); if (creationResult.Status == KeyCredentialStatus.Success) { Unlock(); } else { BiometricsButton.Visibility = Visibility.Visible; } } } else { PassText.Focus(FocusState.Keyboard); } } catch { } }
/// <summary> /// Task to call the "configure-ap" command to a Particle Device in Listening mode /// </summary> /// <param name="index">Index for this cofiguration</param> /// <param name="scanAP">The SoftAPScanAP to use</param> /// <param name="password">The unencrypted password for the WiFi connection</param> /// <param name="publicKey">The publi key from the device</param> /// <returns>Returns response code</returns> public static async Task <int> SetConfigureAPAsync(int index, SoftAPScanAP scanAP, string password, SoftAPPublicKey publicKey) { var configureAP = new SoftAPConfigureAP(); configureAP.Index = index; configureAP.SSID = scanAP.SSID; configureAP.Security = scanAP.Security; configureAP.Channel = scanAP.Channel; if (configureAP.Security != SecurityType.SecurityOpen) { AsymmetricKeyAlgorithmProvider algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); IBuffer publicKeyBuffer = CryptographicBuffer.DecodeFromHexString(publicKey.Data); var key = algorithm.ImportPublicKey(publicKeyBuffer); IBuffer data = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); IBuffer encryptedData = CryptographicEngine.Encrypt(key, data, null); string encryptedPassword = CryptographicBuffer.EncodeToHexString(encryptedData); configureAP.Password = encryptedPassword; } var configureAPString = JsonConvert.SerializeObject(configureAP, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string responseContent = await SendSoftAPCommandAsync(SetupCommand.ConfigureAP, configureAPString); if (responseContent == null) { return(-1); } var result = JToken.Parse(responseContent); var responseCode = (int)result["r"]; return(responseCode); }
private void login_button_Click(object sender, RoutedEventArgs e) { //Todo if (!isEmailLegal(email_textbox.Text)) { // return; } if (!isPasswordLegal(password_textbox.Password)) { // return; } HashAlgorithmProvider hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256); Windows.Storage.Streams.IBuffer hash_result = hash.HashData(CryptographicBuffer.ConvertStringToBinary(password_textbox.Password, BinaryStringEncoding.Utf8)); string password_result = CryptographicBuffer.EncodeToHexString(hash_result); Frame frame = Window.Current.Content as Frame; frame.Navigate(typeof(GoodNightPage)); }
public static byte[] WinRTEncrypt(string publicKey, string data) { if (string.IsNullOrEmpty(data)) { return(new byte[0]); } IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey); AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Capi1PublicKey); IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8); IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null); byte[] encryptedBytes; CryptographicBuffer.CopyToByteArray(encryptedBuffer, out encryptedBytes); return(encryptedBytes); }
public static void AsymmetricEncrypt( string stringToEncrypt, IBuffer buffPublicKey, out string encryptedString) { // Open the algorithm provider for the specified asymmetric algorithm. AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); // Import the public key from a buffer. CryptographicKey publicKey = objAlgProv.ImportPublicKey(buffPublicKey); // Convert string to encrypt to big endian IBuffer buffStringToEncrypt = CryptographicBuffer.ConvertStringToBinary(stringToEncrypt, BinaryStringEncoding.Utf16BE); // Encrypt the session key by using the public key. IBuffer encryptedBuffer = CryptographicEngine.Encrypt(publicKey, buffStringToEncrypt, null); // Encode encrypted string to base64 encryptedString = CryptographicBuffer.EncodeToBase64String(encryptedBuffer); }
/// <summary> /// Generates an encryption key derived using a password, a random salt, and specified number of rounds of PBKDF2 /// /// TODO: pass in password via SecureString? /// </summary> /// <param name="password"></param> /// <param name="salt"></param> /// <returns></returns> public static IBuffer GetEncryptionKey(string password, string salt) { if (string.IsNullOrEmpty(password)) { throw new ArgumentException("Password is empty"); } if (salt == null || salt.Length == 0) { throw new ArgumentException("Salt is empty"); } KeyDerivationAlgorithmProvider pbkdf2 = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1); IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); CryptographicKey key = pbkdf2.CreateKey(buffSecret); KeyDerivationParameters parameters = KeyDerivationParameters.BuildForPbkdf2(CryptographicBuffer.DecodeFromBase64String(salt), PBKDF2_ITERATIONS); return(CryptographicEngine.DeriveKeyMaterial(key, parameters, KEY_SIZE_BYTES)); }
private async Task <byte[]> GetSignedKeyAsync(string keyPhrase) { var openKeyResult = await KeyCredentialManager.OpenAsync(AccountId); if (openKeyResult.Status == KeyCredentialStatus.Success) { var userKey = openKeyResult.Credential; var buffer = CryptographicBuffer.ConvertStringToBinary( keyPhrase, BinaryStringEncoding.Utf8 ); var signResult = await userKey.RequestSignAsync(buffer); if (signResult.Status == KeyCredentialStatus.Success) { return(signResult.Result.ToArray()); } } return(null); }
public static async Task <String> SampleUnprotectData( String stringProtected, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { // Create a DataProtectionProvider object. DataProtectionProvider provider = new DataProtectionProvider(); IBuffer buffProtected = CryptographicBuffer.ConvertStringToBinary(stringProtected, BinaryStringEncoding.Utf16BE); // Decrypt the protected message specified on input. IBuffer buffUnprotected = await provider.UnprotectAsync(buffProtected); // 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. String strClearText = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotected); // Return the plaintext string. return(strClearText); }
//public LoginVM() //{ // LoginCommand = new RelayCommand(IzvrsiLogin); //} protected string GenerateHashFromString(string strMsg) { string strAlgName = HashAlgorithmNames.Md5; IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8); HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName); strAlgName = objAlgProv.AlgorithmName; IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg); if (buffHash.Length != objAlgProv.HashLength) { throw new Exception("There was an error creating the hash"); } string hex = CryptographicBuffer.EncodeToHexString(buffHash); return(hex); }
public async Task TestDataProtectionProviderForStringFalse() { const string input = "The quick brown fox jumps over the lazy dog."; const string expected = null; // Protect value IBuffer pBuffer = await dppSvc.ProtectAsync(input); // Create other (raw) buffer var rBuffer = CryptographicBuffer.ConvertStringToBinary(input, dppSvc.Encoding); // Compare proteted buffer and raw buffer Assert.IsFalse(CryptographicBuffer.Compare(pBuffer, rBuffer)); // Unprotect data string actual = await dppSvc.UnprotectAsync(rBuffer); // Check if value is unprotected successfully Assert.AreEqual(expected, actual); }
public string Encrypt(string unencryptedText) { // Generate a key and IV from the password and salt IBuffer aesKeyMaterial; IBuffer iv; uint iterationCount = 10000; GenerateKeyMaterial(_password, _salt, iterationCount, out aesKeyMaterial, out iv); IBuffer plainText = CryptographicBuffer.ConvertStringToBinary(unencryptedText, BinaryStringEncoding.Utf8); // Setup an AES key, using AES in CBC mode and applying PKCS#7 padding on the input SymmetricKeyAlgorithmProvider aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); CryptographicKey aesKey = aesProvider.CreateSymmetricKey(aesKeyMaterial); // Encrypt the data and convert it to a Base64 string IBuffer encrypted = CryptographicEngine.Encrypt(aesKey, plainText, iv); return(CryptographicBuffer.EncodeToBase64String(encrypted)); }
public static string Decrypt(byte[] encryptedData, string pw, string salt) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE); IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData); KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_ SHA1"); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial); string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); return(result); }
/// <summary> /// 加密字符串。 /// </summary> /// <param name="strMsg"></param> /// <returns></returns> public static async Task <IBuffer> TokenEncryptionAsync(string strMsg) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider("LOCAL=user"); try { // Encode the plaintext input message to a buffer. IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8); // Encrypt the message. IBuffer buffProtected = await Provider.ProtectAsync(buffMsg); return(buffProtected); } catch (Exception) { return(null); } }
public string getSaSToken(string uri, int minUntilExpire) { string targetUri = Uri.EscapeDataString(uri.ToLower()).ToLower(); // Add an expiration in seconds to it. long expiresOnDate = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; expiresOnDate += minUntilExpire * 60 * 1000; long expires_seconds = expiresOnDate / 1000; String toSign = targetUri + "\n" + expires_seconds; // Generate a HMAC-SHA256 hash or the uri and expiration using your secret key. MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256); BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; var messageBuffer = CryptographicBuffer.ConvertStringToBinary(toSign, encoding); IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(SasKeyValue, encoding); CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(keyBuffer); IBuffer signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer); string signature = Uri.EscapeDataString(CryptographicBuffer.EncodeToBase64String(signedMessage)); return("SharedAccessSignature sr=" + targetUri + "&sig=" + signature + "&se=" + expires_seconds + "&skn=" + SasKeyName); }
/// <summary> /// This is the click handler for the 'RunSample' button. It is responsible for executing the sample code. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunSample_Click(object sender, RoutedEventArgs e) { String algName = AlgorithmNames.SelectionBoxItem.ToString(); Scenario3Text.Text = ""; // Create a sample message. String Message = "Some message to authenticate"; // Created a MacAlgorithmProvider object for the algorithm specified on input. MacAlgorithmProvider Algorithm = MacAlgorithmProvider.OpenAlgorithm(algName); Scenario3Text.Text += "*** Sample Hmac Algorithm: " + Algorithm.AlgorithmName + "\n"; // Create a key. IBuffer keymaterial = CryptographicBuffer.GenerateRandom(Algorithm.MacLength); CryptographicKey hmacKey = Algorithm.CreateKey(keymaterial); // Sign the message by using the key. IBuffer signature = Windows.Security.Cryptography.Core.CryptographicEngine.Sign( hmacKey, CryptographicBuffer.ConvertStringToBinary(Message, BinaryStringEncoding.Utf8) ); Scenario3Text.Text += " Signature: " + CryptographicBuffer.EncodeToHexString(signature) + "\n"; // Verify the signature. hmacKey = Algorithm.CreateKey(keymaterial); bool IsAuthenticated = Windows.Security.Cryptography.Core.CryptographicEngine.VerifySignature( hmacKey, CryptographicBuffer.ConvertStringToBinary(Message, BinaryStringEncoding.Utf8), signature ); if (!IsAuthenticated) { Scenario3Text.Text += "HashAlgorithmProvider failed to generate a hash of proper length!\n"; return; } }
/// <summary> /// Decrypt a string /// </summary> /// <param name="key">Private key</param> /// <param name="value">Encrypted string in Base64 format</param> /// <returns>Original value</returns> public static string Decrypt(string key, string value) { if (value == string.Empty) { return(string.Empty); } if (key.Length > 16) { key = key.Substring(0, 16); } else { // Fill key while (key.Length < 16) { key += "0"; } } IBuffer val = CryptographicBuffer.DecodeFromBase64String(value); // Use AES, CBC mode with PKCS#7 padding (good default choice) SymmetricKeyAlgorithmProvider aesCbcPkcs7 = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); IBuffer keymaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); // Create an AES 128-bit (16 byte) key CryptographicKey k = aesCbcPkcs7.CreateSymmetricKey(keymaterial); // Creata a 16 byte initialization vector IBuffer iv = keymaterial;// CryptographicBuffer.GenerateRandom(aesCbcPkcs7.BlockLength); //IBuffer val = CryptographicBuffer.DecodeFromBase64String(value); IBuffer buff = CryptographicEngine.Decrypt(k, val, iv); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buff)); }
/// <summary> /// Encrypt a string /// </summary> /// <param name="key">Private key</param> /// <param name="value">Value to be encrypted</param> /// <returns>Base64 encoded string</returns> public static string Encrypt(string key, string value) { if (value == string.Empty) { return(string.Empty); } // Private key has to be exactly 16 characters if (key.Length > 16) { // Cut of the end if it exceeds 16 characters key = key.Substring(0, 16); } else { // Append zero to make it 16 characters if the provided key is less while (key.Length < 16) { key += "0"; } } // We'll be using AES, CBC mode with PKCS#7 padding to encrypt SymmetricKeyAlgorithmProvider aesCbcPkcs7 = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // Convert the private key to binary IBuffer keymaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); // Create the private key CryptographicKey k = aesCbcPkcs7.CreateSymmetricKey(keymaterial); // Creata a 16 byte initialization vector IBuffer iv = keymaterial; // Encrypt the data byte[] plainText = Encoding.UTF8.GetBytes(value); // Data to encrypt IBuffer buff = CryptographicEngine.Encrypt(k, CryptographicBuffer.CreateFromByteArray(plainText), iv); return(CryptographicBuffer.EncodeToBase64String(buff)); }
/// <summary> /// シグネチャの生成 /// </summary> private string GenerateSignature(SortedDictionary <string, string> paramDictionary, string reqestUrl, string oAuthTokenSecret = null) { string signature = String.Empty; //パラメータディクショナリ内の要素を結合しシグネチャのベースとなる文字列を生成 string baseStrParams = String.Empty; foreach (var kvp in paramDictionary) { baseStrParams += (baseStrParams.Length > 0 ? "&" : String.Empty) + kvp.Key + "=" + kvp.Value; } string baseStr = "POST&" + Uri.EscapeDataString(reqestUrl) + "&" + Uri.EscapeDataString(baseStrParams); //デジタル署名用キーを生成するためのキー文字列を生成 string stringKey = Uri.EscapeDataString(_oauth_consumer_secret) + "&"; if (!String.IsNullOrEmpty(oAuthTokenSecret)) { stringKey += Uri.EscapeDataString(oAuthTokenSecret); } //キー文字列をバッファに変換 IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(stringKey, BinaryStringEncoding.Utf8); //MACアルゴリズムを指定 MacAlgorithmProvider macAlgorithm = MacAlgorithmProvider.OpenAlgorithm(_macAlgorithm); //デジタル署名用キーの生成 CryptographicKey MacKey = macAlgorithm.CreateKey(KeyMaterial); //ベース文字列をバッファに変換 IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(baseStr, BinaryStringEncoding.Utf8); //ベース文字列をデジタル署名 IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned); //Base64エンコードにてシグネチャを取得 signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer); return(signature); }
// Generate an authorization header. public Windows.Web.Http.Headers.HttpCredentialsHeaderValue AuthorizationHeader(string method, DateTime now, HttpRequestMessage request, long contentLength, string ifMatch = "", string md5 = "") { string MessageSignature; if (IsTableStorage) { MessageSignature = String.Format("{0}\n\n{1}\n{2}\n{3}", method, "application/atom+xml", now.ToString("R", System.Globalization.CultureInfo.InvariantCulture), GetCanonicalizedResource(request.RequestUri, StorageAccount) ); } else { MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}", method, (method == "GET" || method == "HEAD") ? String.Empty : contentLength.ToString(), ifMatch, GetCanonicalizedHeaders(request), GetCanonicalizedResource(request.RequestUri, StorageAccount), md5 ); } //Debug.WriteLine(MessageSignature); var key = CryptographicBuffer.DecodeFromBase64String(StorageKey); var msg = CryptographicBuffer.ConvertStringToBinary(MessageSignature, BinaryStringEncoding.Utf8); MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256); //CryptographicKey cryptKey = objMacProv.CreateKey(key); //var buff = CryptographicEngine.Sign(cryptKey, msg); CryptographicHash hash = objMacProv.CreateHash(key); hash.Append(msg); var authorizationHeader = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("SharedKey", StorageAccount + ":" + CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset())); //Debug.WriteLine(authorizationHeader.ToString()); return(authorizationHeader); }
public static string HashString(string str) //This class returns the SHA1 hash of a string { // Convert the message string to binary data. IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8); // Create a HashAlgorithmProvider object. HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1); // Demonstrate how to retrieve the name of the hashing algorithm. String strAlgNameUsed = objAlgProv.AlgorithmName; // Hash the message. IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg); // Convert the hash to a string String strHashBase64 = CryptographicBuffer.EncodeToHexString(buffHash); // Return the encoded string return(strHashBase64); }