public string Decrypt(string content) { // Nome dell'algoritmo da utilizzare per ottenere il provider // Triplo DES con pacchetti da 7 string algName = SymmetricAlgorithmNames.TripleDesEcbPkcs7; // Ottiene il provider SymmetricKeyAlgorithmProvider keyProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algName); // Ottiene la password in formato buffer IBuffer bufferKey = CryptographicBuffer.ConvertStringToBinary(ApplyPadding(Password), BinaryStringEncoding.Utf8); // La chiave per il triple DES deve esseere da 56 bit (56*3 = 168 bit). if (bufferKey.Length % 56 != 0) { throw new Exception("The key lenght is not a multiple of 56 bit."); } // Ottiene la chiave CryptographicKey key = keyProv.CreateSymmetricKey(bufferKey); // Ottiene dalla stringa il buffer del testo da decriptare IBuffer dataText = CryptographicBuffer.DecodeFromHexString(content); string text = ""; if (dataText != null && dataText.Length > 0) { // Decripta IBuffer decriptText = CryptographicEngine.Decrypt(key, dataText, null); // Trasforma il testo da IBuffer a esadecimale. text = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decriptText); } return(text); }
/// <summary> /// Implements RFC2898 Password Based Key Derivation Function #2 /// </summary> /// <param name="password">password to be used as hash key</param> /// <param name="salt">salt</param> /// <param name="iterationCount">number of iterations to perform</param> /// <param name="keyBitLength">desired key length in bits to detive</param> /// <param name="prf">Pseudo Random Function, HMAC will be inited with key equal to given password</param> /// <returns></returns> public static byte[] DeriveKey([ReadOnlyArray] byte[] password, [ReadOnlyArray] byte[] salt, int iterationCount, int keyBitLength, MacAlgorithmProvider prf) { CryptographicKey key = prf.CreateKey(CryptographicBuffer.CreateFromByteArray(password)); // 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and stop. Ensure.MaxValue(keyBitLength, 4294967295, "PBKDF2 expect derived key size to be not more that (2^32-1) bits, but was requested {0} bits.", keyBitLength); int hLen = (int)prf.MacLength; //size of mac in bytes int dkLen = keyBitLength >> 3; //size of derived key in bytes int l = (int)Math.Ceiling(dkLen / (double)hLen); // l = CEIL (dkLen / hLen) , int r = dkLen - (l - 1) * hLen; // r = dkLen - (l - 1) * hLen . byte[][] T = new byte[l][]; for (int i = 0; i < l; i++) { T[i] = F(salt, iterationCount, i + 1, key); // T_l = F (P, S, c, l) } T[l - 1] = Arrays.LeftmostBits(T[l - 1], r * 8); //truncate last block to r bits return(Arrays.Concat(T)); // DK = T_1 || T_2 || ... || T_l<0..r-1> }
private static async Task <bool> RegisterPassportCredentialWithServerAsync(IBuffer publicKey, string userId) { // Include the name of the current device for the benefit of the user. // The server could support a Web interface that shows the user all the devices they // have signed in from and revoke access from devices they have lost. var hostNames = NetworkInformation.GetHostNames(); var localName = hostNames.FirstOrDefault(name => name.DisplayName.Contains(".local")); string computerName = localName.DisplayName.Replace(".local", ""); var registerResult = await PlayFab.PlayFabClientAPI.RegisterWithWindowsHelloAsync(new RegisterWithWindowsHelloRequest { DeviceName = computerName, PublicKey = CryptographicBuffer.EncodeToBase64String(publicKey), UserName = userId }); if (registerResult.Error != null) { return(false); } return(true); }
public async Task StoredDataIsOverwritable() { Assert.IsNull( await this.credentialProvider.GetRawKeyAsync(this.storedCandidate.FileName), "StoredCandidate should not be stored yet" ); byte[] overwriteData = Enumerable.Range(0, 256).Reverse().Select(i => (byte)i).ToArray(); IBuffer overwriteBuffer = CryptographicBuffer.CreateFromByteArray(overwriteData); Assert.IsTrue(await this.credentialProvider.TryStoreRawKeyAsync(this.storedCandidate.FileName, this.mockPasswordBuffer)); Assert.IsTrue( await this.credentialProvider.TryStoreRawKeyAsync(this.storedCandidate.FileName, overwriteBuffer), "Storing data twice for a database should be fine" ); IBuffer retrievedData = await this.credentialProvider.GetRawKeyAsync(this.storedCandidate.FileName); Assert.IsNotNull(retrievedData); Assert.IsTrue( CryptographicBuffer.Compare(overwriteBuffer, retrievedData), "The retrieved data should be what was stored most recently for the database" ); }
public IBuffer getSalt(string username) { IBuffer saltBuffer = null; try { PasswordCredential credential = vault.Retrieve(vaultID, username); if (credential != null) { credential.RetrievePassword(); JObject jsonEntries = JObject.Parse(credential.Password); string saltString = jsonEntries.GetValue(JSONStoreConstants.JSON_STORE_KEY_SALT).ToString(); saltBuffer = CryptographicBuffer.DecodeFromHexString(saltString); } } catch (Exception) { //log error message } return(saltBuffer); }
private async Task <bool> PutAsync <TEntity>(string name, TEntity entity, bool secure) { try { var json = Serializer.Serialize(entity); if (secure) { await SecureStorage.SetAsync(name, json); } else { var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting); var buffer = CryptographicBuffer.ConvertStringToBinary(json, BinaryStringEncoding.Utf8); await FileIO.WriteBufferAsync(file, buffer); } return(true); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("*** LocalStorageManager.PutAsync - Exception: {0}", ex); return(false); } }
/// <summary> /// Дешифрования текст /// </summary> /// <param name="SourceText">Исходный (шифрованный) текст</param> /// <param name="InputKey">Ключ шифрования</param> /// <param name="AlgorytmName">Имя алгоритма дешифрования</param> /// /// <returns>Расшифрованный (открытый) текст</returns> public string DecrypMode(string SourceText, string InputKey, string AlgorytmName, string IV, string KeySize) { SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorytmName); IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE); //CryptoKey = Algorithm.CreateSymmetricKey(keymaterial); KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, Convert.ToUInt32(KeySize) / 8); // string test= CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial); CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial); if (AlgorytmName.Contains("CBC")) { IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE); } // Set the data to encrypt. SourceTextBuffer = CryptographicBuffer.DecodeFromBase64String(SourceText); // Decrypt DecryptBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(CryptoKey, SourceTextBuffer, IVBuffer); DecryptTextOutput = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, DecryptBuffer);//Надо думать над реализацией Base64 return(DecryptTextOutput); }
// Encryption and authentication method private void AuthenticatedEncryption( String strMsg, String strAlgName, UInt32 keyLength) { // Open a SymmetricKeyAlgorithmProvider object for the specified algorithm. SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // Create a buffer that contains the data to be encrypted. encoding = BinaryStringEncoding.Utf8; IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Generate a symmetric key. keyMaterial = CryptographicBuffer.GenerateRandom(keyLength); keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial); key = objAlgProv.CreateSymmetricKey(keyMaterial); // Generate a new nonce value. buffNonce = GetNonce(); // Encrypt and authenticate the message. EncryptedAndAuthenticatedData objEncrypted = CryptographicEngine.EncryptAndAuthenticate( key, buffMsg, buffNonce, null); encryptedMessageData = objEncrypted.EncryptedData; authenticationTag = objEncrypted.AuthenticationTag; encryptedMessageDataString = CryptographicBuffer.EncodeToBase64String(encryptedMessageData); authenticationTagString = CryptographicBuffer.EncodeToBase64String(authenticationTag); nonceString = CryptographicBuffer.EncodeToBase64String(buffNonce); plaintext = encryptedMessageDataString; tag.Text = authenticationTagString; nonce.Text = nonceString; }
public static int GetColorIndex(int id) { return(id % 6); if (id < 0) { id += 256; } try { var str = string.Format("{0}{1}", id, MTProtoService.Current.CurrentUserId); if (str.Length > 15) { str = str.Substring(0, 15); } var input = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8); //if (input.Length > 16) //{ // byte[] temp; // CryptographicBuffer.CopyToByteArray(input, out temp); // input = CryptographicBuffer.CreateFromByteArray(temp.Take(16).ToArray()); //} var hasher = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); var hashed = hasher.HashData(input); byte[] digest; CryptographicBuffer.CopyToByteArray(hashed, out digest); return(digest[id % 0x0F] & 0x07); } catch { } return(id % 8); }
public IAsyncOperation <IInputStream> UriToStreamAsync(System.Uri uri) { // The WebView's buildLocalStreamUri method takes contentIdentifier and relativePath // parameters to generate a URI of the form: // ms-local-stream://<package name>_<encoded contentIdentifier>/<relativePath> // The resolver can decode the contentIdentifier to determine what content should be // returned in the output stream. 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-appdata:///local/" + contentIdentifier + relativePath); return(GetFileStreamFromApplicationUriAsync(appDataUri).AsAsyncOperation()); }
private void nfcChatButton_Click(object sender, RoutedEventArgs e) { if (lastSelected.isOnline == false) { this.PrintMessage("User is not online, cannot start chat."); return; } if (lastSelected.sessionEstablished) { lastSelected.chatButtonsVisible = false; lastSelected = null; this.Frame.Navigate(typeof(ChatPage)); return; } if (AppServices.myProximityDevice == null) { AppServices.myProximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault(); if (AppServices.myProximityDevice == null) { this.PrintMessage("Unable to get NFC chip. This device might not be capable of proximity interactions or NFC is disabled in settings"); return; } AppServices.myProximityDevice.DeviceArrived += ProximityDeviceArrived; AppServices.myProximityDevice.DeviceDeparted += ProximityDeviceDeparted; } int compareResult = string.Compare(AppServices.localUsernameEncrypted, lastSelected.encryptedUsername); this.keyBuff = null; // My username is greater so I generate a key if (compareResult > 0) { keyBuff = CryptographicBuffer.GenerateRandom(256); } PrintMessage("Please close this message and then tap and hold the devices together"); }
/// <summary> /// Decrypt buffer using password. /// </summary> /// <param name="data">Data buffer to decrypt.</param> /// <param name="key">Key that is used for decryption.</param> /// <returns>Returns the decrypted value as string.</returns> public string Decrypt(IBuffer data, string key) { // Create a Sha256 from key. var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); var hashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256); IBuffer keyMaterial = hashProvider.HashData(passwordBuffer); // Create am Aes256 with CBC and Pkcs7. var aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); CryptographicKey aesKey = aesProvider.CreateSymmetricKey(keyMaterial); // Split data into IV and encrypted data. IBuffer iv = CryptographicBuffer.CreateFromByteArray(new byte[aesProvider.BlockLength]); IBuffer encrypted = CryptographicBuffer.CreateFromByteArray(new byte[data.Length - iv.Length]); data.CopyTo(0, iv, 0, iv.Length); data.CopyTo(iv.Length, encrypted, 0, encrypted.Length); // Decrypt data. IBuffer decrypted = CryptographicEngine.Decrypt(aesKey, encrypted, iv); string value = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decrypted); return(value); }
/// <summary> /// Read a stream and return it's MD5, does not reset or close the stream. /// </summary> /// <param name="stream"></param> /// <returns></returns> public static string GetMD5(this Stream stream) { #if NETFX_CORE var alg = HashAlgorithmProvider.OpenAlgorithm("MD5"); IBuffer buff; if (stream is MemoryStream) { buff = WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(stream as MemoryStream); } else //In case it returned a non-Memory stream. { MemoryStream ms = new MemoryStream(); CopyStream(stream, ms); buff = WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(ms); } var hashed = alg.HashData(buff); return(CryptographicBuffer.EncodeToHexString(hashed)); #else MD5CryptoServiceProvider csp = new MD5CryptoServiceProvider(); byte[] hash = csp.ComputeHash(stream); return(BitConverter.ToString(hash).Replace("-", "").ToLower()); #endif }
public keyGenerator(string pass, out string publicToUpload, out string privateToUpload, out string hash, out string salt) { // Create an asymmetric key pair. String strAsymmetricAlgName = AsymmetricAlgorithmNames.RsaPkcs1; UInt32 asymmetricKeyLength = 512; IBuffer buffPublicKey; // public IBuffer buffKeyPair; this.SampleCreateAsymmetricKeyPair( strAsymmetricAlgName, asymmetricKeyLength, out buffPublicKey, out buffKeyPair); // Public key simply uploaded as a BE string // publicToUpload = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16BE, buffPublicKey); publicToUpload = CryptographicBuffer.EncodeToBase64String(buffPublicKey); // Private key - encrypt with pass string strKeyPair = CryptographicBuffer.EncodeToBase64String(buffKeyPair); privateToUpload = Encrypt(strKeyPair, pass); string encryptedString, decryptedString; AsymmetricEncrypt("kutya", publicToUpload, out encryptedString); AsymmetricDecrypt(strKeyPair, encryptedString, out decryptedString); Debug.WriteLine(decryptedString); salt = GenerateRandomData(); string saltedPass = pass + salt; // Hash pashword with salt IBuffer hashBuffer = GetMD5Hash(saltedPass); // everything to base64 hash = CryptographicBuffer.EncodeToBase64String(hashBuffer); // CryptographicEngine.Encrypt( }
public async Task Headers_should_detect_partial_support_format() { using (var database = TestFiles.Read("IO.Demo7Pass.kdbx")) using (var file = new InMemoryRandomAccessStream()) { var buffer = WindowsRuntimeBuffer.Create(512); buffer = await database.ReadAsync( buffer, 512, InputStreamOptions.None); await file.WriteAsync(buffer); file.Seek(8); // Schema; 3.Max await file.WriteAsync(CryptographicBuffer .DecodeFromHexString("FFFF0300")); file.Seek(0); var result = await FileFormat.Headers(file); Assert.NotNull(result.Headers); Assert.Equal(FileFormats.PartialSupported, result.Format); } }
private CryptographicHash CreateHashCryptographicHash() { String algName = AlgorithmNames.SelectionBoxItem.ToString(); // Create a HashAlgorithmProvider object. HashAlgorithmProvider Algorithm = HashAlgorithmProvider.OpenAlgorithm(algName); IBuffer vector = CryptographicBuffer.DecodeFromBase64String("uiwyeroiugfyqcajkds897945234=="); HashingText.Text += "\n*** Sample Hash Algorithm: " + Algorithm.AlgorithmName + "\n"; HashingText.Text += " Initial vector: uiwyeroiugfyqcajkds897945234==\n"; // Compute the hash in one call. digest = Algorithm.HashData(vector); if (digest.Length != Algorithm.HashLength) { HashingText.Text += "HashAlgorithmProvider failed to generate a hash of proper length!\n"; return(null); } HashingText.Text += " Hash: " + CryptographicBuffer.EncodeToHexString(digest) + "\n"; return(Algorithm.CreateHash()); }
private async Task <Result> SignInWithWindowsHelloAsync() { string userName = AppSettings.Current.UserName; if (IsWindowsHelloEnabled(userName)) { var retrieveResult = await KeyCredentialManager.OpenAsync(userName); if (retrieveResult.Status == KeyCredentialStatus.Success) { var credential = retrieveResult.Credential; var challengeBuffer = CryptographicBuffer.DecodeFromBase64String("challenge"); var result = await credential.RequestSignAsync(challengeBuffer); if (result.Status == KeyCredentialStatus.Success) { return(Result.Ok()); } return(Result.Error("Windows Hello", $"Cannot sign in with Windows Hello: {result.Status}")); } return(Result.Error("Windows Hello", $"Cannot sign in with Windows Hello: {retrieveResult.Status}")); } return(Result.Error("Windows Hello", "Windows Hello is not enabled for current user.")); }
public async static Task <byte[]> Decrypt(string filePath) { byte[] fileBytes = await FileManager.ReadBytesFromFile(filePath); IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(key1, BinaryStringEncoding.Utf8); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(key2, BinaryStringEncoding.Utf16LE); IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(fileBytes); // 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); byte[] result; CryptographicBuffer.CopyToByteArray(resultBuffer, out result); return(result); }
public List <UploadOperation> CreateUpload(DavItem item, List <StorageFile> files) { List <UploadOperation> result = new List <UploadOperation>(); BackgroundUploader uploader = new BackgroundUploader(); uploader.Method = "PUT"; var buffer = CryptographicBuffer.ConvertStringToBinary(Configuration.UserName + ":" + Configuration.Password, BinaryStringEncoding.Utf8); var token = CryptographicBuffer.EncodeToBase64String(buffer); var value = new HttpCredentialsHeaderValue("Basic", token); uploader.SetRequestHeader("Authorization", value.ToString()); foreach (var storageFile in files) { var uri = new Uri(item.EntityId.TrimEnd('/'), UriKind.RelativeOrAbsolute); uri = new Uri(uri + "/" + storageFile.Name, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = CreateItemUri(uri); } UploadOperation upload = uploader.CreateUpload(uri, storageFile); result.Add(upload); } return(result); }
public static byte[] HmacData(TpmAlgId hashAlgId, byte[] key, byte[] dataToHash) { string algName; switch (hashAlgId) { case TpmAlgId.Sha1: algName = MacAlgorithmNames.HmacSha1; break; case TpmAlgId.Sha256: algName = MacAlgorithmNames.HmacSha256; break; case TpmAlgId.Sha384: algName = MacAlgorithmNames.HmacSha384; break; case TpmAlgId.Sha512: algName = MacAlgorithmNames.HmacSha512; break; default: Globs.Throw <ArgumentException>("HmacData(): Unsupported hash algorithm " + hashAlgId); return(null); } MacAlgorithmProvider algProvider = MacAlgorithmProvider.OpenAlgorithm(algName); CryptographicHash hash = algProvider.CreateHash(CryptographicBuffer.CreateFromByteArray(key)); hash.Append(CryptographicBuffer.CreateFromByteArray(dataToHash)); IBuffer hmacBuffer = hash.GetValueAndReset(); byte[] hmac; CryptographicBuffer.CopyToByteArray(hmacBuffer, out hmac); return(hmac); }
/// <summary> /// Decypts a string using a key signed by a KeyCredential. /// </summary> /// <param name="strProtected">Text to decrypt.</param> /// <param name="rResult">KeyCredential object used to sign a key to encrypt the text.</param> /// <returns>Decrypted text.</returns> internal static async Task <ProtectedString> Decrypt(string strProtected, KeyCredentialRetrievalResult rResult) { // The same text must be used to decrypt the data Assembly assembly = Assembly.GetExecutingAssembly(); var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0]; var id = attribute.Value; IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(id, encoding); // Start a background thread to ensure Windows Security prompt is opened in foreground var _ = Task.Factory.StartNew(() => EnsureForeground()); // The actual Signing of the string KeyCredentialOperationResult opResult = await rResult.Credential.RequestSignAsync(buffMsg); if (opResult.Status == KeyCredentialStatus.Success) { IBuffer signedData = opResult.Result; // Creation of the key with the signed string SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); CryptographicKey myKey = provider.CreateSymmetricKey(signedData); // Decryption of the data using the key created (mKey) IBuffer buffProtected = CryptographicBuffer.DecodeFromBase64String(strProtected); CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(myKey, buffProtected, null), out var ba); ProtectedString ps = new ProtectedString(true, ba); MemUtil.ZeroByteArray(ba); return(ps); } else { WinHelloUnlockExt.opened = true; WinHelloErrors(opResult.Status, "Error decrypting the data: "); return(null); } }
private async void tbTerminal_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args) { if (tbTerminal.Text == "") { return; } int i; for (i = 0; i < tbTerminal.Text.Length; i++) { string text = tbTerminal.Text.Substring(i, 1); var data = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8); var attrinfo = cbCharacteristics.SelectedItem as BluetoothLEAttributeDisplay; if (attrinfo == null) { return; } var characteristic = attrinfo.characteristic; try { var result = await characteristic.WriteValueAsync(data); if (result == GattCommunicationStatus.Success) { tbResponse.Text += text; } } catch (Exception ex) when((uint)ex.HResult == 0x80650003 || (uint)ex.HResult == 0x80070005) { } } tbTerminal.Text = ""; }
/// <summary> /// Creates an RSA PKCS#1 v1.5 signature of a SHA1 for the stream. /// </summary> private static byte[] RsaPkcs15Sha1_Sign( ArraySegment <byte> dataToSign, X509Certificate2 signingCertificate) { // extract the private key. RSA rsa = null; try { rsa = signingCertificate.GetRSAPrivateKey(); } catch (Exception ex) { throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate: " + ex.Message); } if (rsa == null) { throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate."); } // compute the hash of message. MemoryStream istrm = new MemoryStream(dataToSign.Array, dataToSign.Offset, dataToSign.Count, false); HashAlgorithmProvider sha1Provider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1); IBuffer buffer = CryptographicBuffer.CreateFromByteArray(istrm.ToArray()); buffer = sha1Provider.HashData(buffer); byte[] digest = new byte[buffer.Length]; CryptographicBuffer.CopyToByteArray(buffer, out digest); istrm.Dispose(); // create the signature. return(rsa.SignHash(digest, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)); }
public byte[] Export(string bcryptBlobType) { if (string.IsNullOrEmpty(bcryptBlobType)) { return(null); } IBuffer buf; if (bcryptBlobType == BCRYPT_RSAPRIVATE_BLOB) { buf = Key.Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey); } else if (bcryptBlobType == BCRYPT_RSAPUBLIC_BLOB) { buf = Key.ExportPublicKey(CryptographicPublicKeyBlobType.BCryptPublicKey); } else { return(null); } byte[] keyBlob; CryptographicBuffer.CopyToByteArray(buf, out keyBlob); return(keyBlob); }
public static async Task SaveCards(ObservableCollection <StarbucksCard> unprotectedCards) { var protectedCards = new ObservableCollection <StarbucksCard>(); foreach (var unprotectedCard in unprotectedCards) { var protectedCard = new StarbucksCard { Title = unprotectedCard.Title }; // encrypt card number at rest var numberData = CryptographicBuffer.ConvertStringToBinary(unprotectedCard.AccountNumber.ToString(), BinaryStringEncoding.Utf8); var numberDataProtected = await new DataProtectionProvider().ProtectAsync(numberData); protectedCard.AccountNumber = Convert.ToInt64(numberDataProtected); // encrypt scanned data at rest var scanData = CryptographicBuffer.ConvertStringToBinary(unprotectedCard.ScannedData, BinaryStringEncoding.Utf8); var scanDataProtected = await new DataProtectionProvider().ProtectAsync(scanData); protectedCard.ScannedData = Convert.ToString(scanDataProtected); } RoamingSettings.Values["StarbucksCards"] = JsonConvert.SerializeObject(protectedCards); }
public static byte[] GenerateKeyBytes(int keySize) { #if WINDOWS_UWP Windows.Storage.Streams.IBuffer keyBytesBuffer = CryptographicBuffer.GenerateRandom((uint)keySize); byte[] keyBytes; CryptographicBuffer.CopyToByteArray(keyBytesBuffer, out keyBytes); #elif NETSTANDARD1_3 var keyBytes = new byte[keySize]; using (var cyptoProvider = System.Security.Cryptography.RandomNumberGenerator.Create()) { while (keyBytes.Contains(byte.MinValue)) { cyptoProvider.GetBytes(keyBytes); } } #else var keyBytes = new byte[keySize]; using (var cyptoProvider = new RNGCryptoServiceProvider()) { cyptoProvider.GetNonZeroBytes(keyBytes); } #endif return(keyBytes); }
private string HashString(string algorithmName, string stringValue) { // Convert the message string to binary data. IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(stringValue, BinaryStringEncoding.Utf8); // Create a HashAlgorithmProvider object. HashAlgorithmProvider hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm(algorithmName); // Hash the message. IBuffer buffHash = hashAlgorithmProvider.HashData(buffUtf8Msg); // Verify that the hash length equals the length specified for the algorithm. if (buffHash.Length != hashAlgorithmProvider.HashLength) { //throw new Exception("There was an error creating the hash"); return(null); } // Convert to Hex var hashedStringHexValue = BitConverter.ToString(buffHash.ToArray()); // Get rid of the dashes return(hashedStringHexValue.Replace("-", "")); }
public static void AcceptClient(DatagramSocket listener, DatagramSocketMessageReceivedEventArgs args) { new Task(async() => { // Retrieve client IP info byte[] serverIPBytes = CryptographicBuffer.ConvertStringToBinary(serverIP, BinaryStringEncoding.Utf8).ToArray(); //HostName clientIP = args.RemoteAddress; //string clientPort = args.RemotePort; DataReader reader = args.GetDataReader(); uint numBytesLoaded = await reader.LoadAsync(1024); //byte[] buffer = new byte[reader.UnconsumedBufferLength]; //reader.ReadBytes(buffer); string clientIP = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, reader.ReadBuffer(reader.UnconsumedBufferLength)); DataWriter writer = new DataWriter(await listener.GetOutputStreamAsync(new HostName(clientIP), Config.Ports.FindServer.ToString())); writer.WriteBytes(serverIPBytes); await writer.StoreAsync(); // necessary?? // Reset listening status await listener.ConnectAsync(new HostName("0.0.0.0"), Config.Ports.FindServer.ToString()); }).Start(); }
public static string Encrypt(string text, string nonce) { if (String.IsNullOrWhiteSpace(text)) { return(null); } IBuffer keyMaterial; IBuffer iv; Settings.GenerateKey(out keyMaterial, out iv, nonce); 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); }
private string[] ForFetchTokenDecryption() { var stringColl = new string[2]; try { // password decryption over here. SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); cryptographicKey = objAlg.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(CipherEncryptionHelper.CollForKeyAndIv)); ibufferVector = CryptographicBuffer.CreateFromByteArray(CipherEncryptionHelper.CollForKeyAndIv); if (SettingsHelper.ReadSettingsValue(SettingsConstants.Password) is byte[] Password) // init ibuffer vector and cryptographic key for decryption. { stringColl[1] = CipherEncryptionHelper.CipherDecryption( // decryption the message. SymmetricAlgorithmNames.AesCbcPkcs7, CryptographicBuffer.CreateFromByteArray(Password), ibufferVector, BinaryStringEncoding.Utf8, cryptographicKey); } if (SettingsHelper.ReadSettingsValue(SettingsConstants.Email) is byte[] User) // init ibuffer vector and cryptographic key for decryption. { stringColl[0] = CipherEncryptionHelper.CipherDecryption( // decryption the message. SymmetricAlgorithmNames.AesCbcPkcs7, CryptographicBuffer.CreateFromByteArray(User), ibufferVector, BinaryStringEncoding.Utf8, cryptographicKey); } return(stringColl); } catch (Exception e) { // if any error throws, clear the password cache to prevent more errors. Debug.WriteLine(e.StackTrace); return(null); } }