public string PubnubAccessManagerSign(string key, string data) { string secret = key; string message = data; var encoding = new System.Text.UTF8Encoding(); byte[] keyByte = encoding.GetBytes(secret); byte[] messageBytes = encoding.GetBytes(message); #if NETFX_CORE var hmacsha256 = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256); IBuffer valueBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8); IBuffer buffKeyMaterial = CryptographicBuffer.ConvertStringToBinary(secret, BinaryStringEncoding.Utf8); CryptographicKey cryptographicKey = hmacsha256.CreateKey(buffKeyMaterial); // Sign the key and message together. IBuffer bufferProtected = CryptographicEngine.Sign(cryptographicKey, valueBuffer); DataReader dataReader = DataReader.FromBuffer(bufferProtected); byte[] hashmessage = new byte[bufferProtected.Length]; dataReader.ReadBytes(hashmessage); return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_')); #else using (var hmacsha256 = new HMACSHA256(keyByte)) { byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_')); } #endif }
public void SampleCipherDecryption( 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. String strDecrypted = CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted); }
public SHA1(byte[] hmacKey) { MacAlgorithmProvider hmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); var materialKey = CryptographicBuffer.CreateFromByteArray(hmacKey); macKey = hmacSha1Provider.CreateKey(materialKey); }
public static async Task <string> GetEncryptedPassword(string passWord) { string base64String; try { //https://secure.bilibili.com/login?act=getkey&rnd=4928 //https://passport.bilibili.com/login?act=getkey&rnd=4928 HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter(); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired); httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(httpBaseProtocolFilter); //WebClientClass wc = new WebClientClass(); string stringAsync = await httpClient.GetStringAsync((new Uri("https://passport.bilibili.com/login?act=getkey&rnd=" + new Random().Next(1000, 9999), UriKind.Absolute))); JObject jObjects = JObject.Parse(stringAsync); string str = jObjects["hash"].ToString(); string str1 = jObjects["key"].ToString(); string str2 = string.Concat(str, passWord); string str3 = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim(); byte[] numArray = Convert.FromBase64String(str3); AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0); IBuffer buffer = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null); base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer)); } catch (Exception) { //throw; base64String = passWord; } return(base64String); }
public void createAsymmetricKeyPair( String strAsymmetricAlgName, UInt32 keyLength, out IBuffer buffPublicKey) { // Open the algorithm provider for the specified asymmetric algorithm. AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName); // Demonstrate use of the AlgorithmName property (not necessary to create a key pair). String strAlgName = objAlgProv.AlgorithmName; // Create an asymmetric key pair. CryptographicKey keyPair = objAlgProv.CreateKeyPair(keyLength); // Export the public key to a buffer for use by others. buffPublicKey = keyPair.ExportPublicKey(); //public key to internal buffer DataContainer.senderPublicKey = buffPublicKey; // You should keep your private key (embedded in the key pair) secure. For // the purposes of this example, however, we're just copying it into a // static class variable for later use during decryption. DataContainer.senderKeyPair = keyPair.Export(); }
private string _generateConfirmationHashForTime(long time, string tag) { int n2 = tag != null?Math.Min(40, 8 + tag.Length) : 8; var array = new byte[n2]; for (var n4 = 7; n4 >= 0; n4--) { array[n4] = (byte)time; time >>= 8; } if (tag != null) { Array.Copy(Encoding.UTF8.GetBytes(tag), 0, array, 8, n2 - 8); } try { IBuffer identitySecretArray = CryptographicBuffer.DecodeFromBase64String(this.IdentitySecret); MacAlgorithmProvider hmacsha1 = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); CryptographicKey hmacKey = hmacsha1.CreateKey(identitySecretArray); string encodedData = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Sign(hmacKey, CryptographicBuffer.CreateFromByteArray(array))); string hash = WebUtility.UrlEncode(encodedData); return(hash); } catch (Exception) { return(null); //Fix soon: catch-all is BAD! } }
/// <summary> /// Encrypt ibuffer /// </summary> /// <param name="input">ibuffer to encrypt</param> /// <param name="password">Password to use for encryption</param> /// <returns>Encrypted IBuffer</returns> public static IBuffer Encrypt(IBuffer ibuf) { // get IV, key and encrypt var iv = CryptographicBuffer.CreateFromByteArray(UTF8Encoding.UTF8.GetBytes(EncryptionProvider.PublicKey)); SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc); IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(EncryptionProvider.PublicKey, BinaryStringEncoding.Utf8); CryptographicKey key = provider.CreateSymmetricKey(buffer); // Append the padding (before encrypting) long remainder = ibuf.Length % provider.BlockLength; long newSize = ibuf.Length + provider.BlockLength - remainder; byte[] b; CryptographicBuffer.CopyToByteArray(ibuf, out b); if (newSize > b.Length) { if (b[b.Length - 1] == 0) { b[b.Length - 1] = 1; } Array.Resize(ref b, (int)newSize); } IBuffer binput2 = CryptographicBuffer.CreateFromByteArray(b); IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key, binput2, iv); CryptographicBuffer.CopyToByteArray(encryptedBuffer, out b); return(encryptedBuffer); }
public static string Encrypt(string plainText, string pw, string iv) { IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); IBuffer ivBuffer = CryptographicBuffer.ConvertStringToBinary(iv, BinaryStringEncoding.Utf16LE); IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE); // Derive key material for password size 32 bytes for AES256 algorithm KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); // using iv and 1000 iterations KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(ivBuffer, 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 IV from derived password key IBuffer ivMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); // create symmetric key from derived password key CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); // encrypt data buffer using symmetric key and derived iv material IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, ivMaterial); return(CryptographicBuffer.EncodeToBase64String(resultBuffer)); }
public async Task ShouldGenerateAndValidateJweAndJws() { await WarmupData.Clear(); var handler = new JsonWebTokenHandler(); var now = DateTime.Now; // Generate right now and in memory var newKey = new CryptographicKey(Algorithm.Create(AlgorithmType.RSA, JwtType.Both)); var encryptingCredentials = new EncryptingCredentials(newKey, EncryptionAlgorithmKey.RsaOAEP, EncryptionAlgorithmContent.Aes128CbcHmacSha256); var signingCredentials = new SigningCredentials(newKey, DigitalSignaturesAlgorithm.RsaSsaPssSha256); var claims = new ClaimsIdentity(GenerateClaim().Generate(5)); var descriptorJws = new SecurityTokenDescriptor { Issuer = "me", Audience = "you", IssuedAt = now, NotBefore = now, Expires = now.AddMinutes(5), Subject = claims, SigningCredentials = signingCredentials }; var descriptorJwe = new SecurityTokenDescriptor { Issuer = "me", Audience = "you", IssuedAt = now, NotBefore = now, Expires = now.AddMinutes(5), Subject = claims, EncryptingCredentials = encryptingCredentials }; var jws = handler.CreateToken(descriptorJws); var jwe = handler.CreateToken(descriptorJwe); var result = await handler.ValidateTokenAsync(jws, new TokenValidationParameters { ValidIssuer = "me", ValidAudience = "you", IssuerSigningKey = signingCredentials.Key }); result.IsValid.Should().BeTrue(); result = await handler.ValidateTokenAsync(jwe, new TokenValidationParameters { ValidIssuer = "me", ValidAudience = "you", RequireSignedTokens = false, TokenDecryptionKey = encryptingCredentials.Key }); result.IsValid.Should().BeTrue(); }
public AuthenticationService() { algName = SymmetricAlgorithmNames.AesEcbPkcs7; keyAlgProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algName); randBuffer = CryptographicBuffer.GenerateRandom(keyAlgProvider.BlockLength); randBufCBC = null; cryptKey = keyAlgProvider.CreateSymmetricKey(randBuffer); }
public SHA1(string hmacKey) { MacAlgorithmProvider hmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); var inputBuffer = Encoding.GetEncoding("iso-8859-1").GetBytes(hmacKey); var materialKey = CryptographicBuffer.CreateFromByteArray(inputBuffer); macKey = hmacSha1Provider.CreateKey(materialKey); }
private CryptographicKey SymmetricKeyFromMaterial(string keyMaterial) { IBuffer keyData = CryptographicBuffer.DecodeFromBase64String(keyMaterial); SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(EncryptAlgorithm); CryptographicKey key = provider.CreateSymmetricKey(keyData); return(key); }
public string Decrypt(string encryptedData) { IBuffer binaryData = CryptographicBuffer.DecodeFromBase64String(encryptedData); CryptographicKey key = cryptingProvider.CreateSymmetricKey(GetHash(getUserPassword())); IBuffer decryptedData = CryptographicEngine.Decrypt(key, binaryData, null); return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedData)); }
public string Encrypt(string data) { IBuffer binaryData = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);// Encoding.Unicode.GetBytes(data).AsBuffer(); CryptographicKey key = cryptingProvider.CreateSymmetricKey(GetHash(getUserPassword())); IBuffer encryptedBinaryData = CryptographicEngine.Encrypt(key, binaryData, null); return(CryptographicBuffer.EncodeToBase64String(encryptedBinaryData)); }
public byte[] Sign([ReadOnlyArray] byte[] securedInput, object key) { var sharedKey = Ensure.Type <byte[]>(key, "HmacUsingSha expects key to be byte[] array."); CryptographicKey hmacKey = AlgProvider.CreateKey(CryptographicBuffer.CreateFromByteArray(sharedKey)); return(Buffer.ToBytes(CryptographicEngine.Sign(hmacKey, CryptographicBuffer.CreateFromByteArray(securedInput)))); }
public OTP(string key) { MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1); IBuffer keyMaterial = CryptographicBuffer.CreateFromByteArray(key.ToBytesBase32()); cKey = provider.CreateKey(keyMaterial); }
public static byte[] buildRemoveFriendBytes(CryptographicKey encryptionKey = null) { JObject updateObj = new JObject(); updateObj.Add("updateType", "request"); updateObj.Add("requestStatus", "removed"); return(MessageBuilder.buildMessageBytes(updateObj, encryptionKey)); }
public static byte[] bulidSessionEstablishedBytes(CryptographicKey encryptionKey = null) { JObject updateObj = new JObject(); updateObj.Add("updateType", "session"); return(MessageBuilder.buildMessageBytes(updateObj, encryptionKey)); }
public static string HashWith(this string input, MacAlgorithmProvider hashProvider, string key) { IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); CryptographicKey cryptoKey = hashProvider.CreateKey(keyMaterial); IBuffer hash = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8)); return(CryptographicBuffer.EncodeToBase64String(hash)); }
/// <summary> /// Asynchronously transforms the user's 32-byte key using ECB AES. /// /// Since Rijndael works on 16-byte blocks, the k is split in half and /// each half is encrypted separately the same number of times. /// </summary> /// <param name="rawKey">The key to transform.</param> /// <param name="token">Token used to cancel the transform task.</param> /// <returns>The transformed key.</returns> public async Task <IBuffer> TransformKeyAsync(IBuffer rawKey, CancellationToken token) { if (rawKey == null) { throw new ArgumentNullException(nameof(rawKey)); } if (rawKey.Length != 32) { throw new ArgumentException("Key must be 32 bytes", nameof(rawKey)); } // Split the k buffer in half byte[] rawKeyBytes = rawKey.ToArray(); IBuffer lowerBuffer = WindowsRuntimeBuffer.Create(rawKeyBytes, 0, 16, 16); IBuffer upperBuffer = WindowsRuntimeBuffer.Create(rawKeyBytes, 16, 16, 16); // Set up the encryption parameters var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); CryptographicKey key = aes.CreateSymmetricKey(this.algoParams.Seed); IBuffer iv = null; // Run the encryption rounds in two threads (upper and lower) ConditionChecker checkForCancel = () => token.IsCancellationRequested; Task <bool> lowerTask = Task.Run(() => { lowerBuffer = KeePassHelper.TransformKey(this.algoParams.Rounds, this.algoParams.Seed, iv, lowerBuffer, checkForCancel); return(!checkForCancel()); } ); Task <bool> upperTask = Task.Run(() => { upperBuffer = KeePassHelper.TransformKey(this.algoParams.Rounds, this.algoParams.Seed, iv, upperBuffer, checkForCancel); return(!checkForCancel()); } ); // Verify the work was completed successfully await Task.WhenAll(lowerTask, upperTask); if (!(lowerTask.Result && upperTask.Result)) { return(null); } // Copy the units of work back into one buffer, hash it, and return. IBuffer transformedKey = (new byte[32]).AsBuffer(); lowerBuffer.CopyTo(0, transformedKey, 0, 16); upperBuffer.CopyTo(0, transformedKey, 16, 16); var sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256); CryptographicHash hash = sha256.CreateHash(); hash.Append(transformedKey); return(hash.GetValueAndReset()); }
//convert to Task if taking time public byte[] Generate(int length) { Debug.Assert(length > 0); Debug.Assert(_key != null); Debug.Assert(_prevSeed != null); byte[] result = new byte[length]; // Creates an instance of the SymmetricKeyAlgorithmProvider class and opens the specified algorithm for use // SymmetricAlgorithmNames.AesEcb - Retrieves a string that contains "AES_ECB". SymmetricKeyAlgorithmProvider aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); // Creates a buffer from an input byte array IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(_key); // Creates a symmetric key // https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(Windows.Security.Cryptography.Core.SymmetricKeyAlgorithmProvider.CreateSymmetricKey);k(TargetFrameworkMoniker-.NETCore,Version%3Dv5.0);k(DevLang-csharp)&rd=true // https://msdn.microsoft.com/en-us/library/windows/apps/xaml/br241541(v=win.10).aspx?appid=dev14idef1&l=en-us&k=k(windows.security.cryptography.core.symmetrickeyalgorithmprovider.createsymmetrickey)%3bk(targetframeworkmoniker-.netcore,version%3dv5.0)%3bk(devlang-csharp)&rd=true CryptographicKey cryptographicKey = aesProvider.CreateSymmetricKey(keyBuffer); int remainingLength = length; int index = 0; while (remainingLength > 0) { int chunkLength = BtleLinkTypes.ENCRYPTED_BLOCK_SIZE - _offset; chunkLength = remainingLength < chunkLength ? remainingLength : chunkLength; if (_offset == 0) { //byte[ ] initializationVector = new byte[ BtleLinkTypes.ENCRYPTED_BLOCK_SIZE ]; // Creates a buffer from an input byte array //IBuffer ivBuffer = CryptographicBuffer.CreateFromByteArray( initializationVector ); // Creates a buffer from an input byte array IBuffer seedBuffer = CryptographicBuffer.CreateFromByteArray(_prevSeed); // Encrypt the data IBuffer encryptedSeed = CryptographicEngine.Encrypt(cryptographicKey, seedBuffer, null); Debug.Assert(encryptedSeed.Length >= BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); Buffer.BlockCopy(encryptedSeed.ToArray(), 0, _prevSeed, 0, BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); } Buffer.BlockCopy(_prevSeed, _offset, result, index, chunkLength); index += chunkLength; remainingLength -= chunkLength; Debug.Assert(_offset + chunkLength <= BtleLinkTypes.ENCRYPTED_BLOCK_SIZE); _offset = (_offset + chunkLength) % BtleLinkTypes.ENCRYPTED_BLOCK_SIZE; } Debug.Assert(result.Length == length); return(result); }
private static byte[] AesDec(byte[] sharedKey, byte[] cipherText) { SymmetricKeyAlgorithmProvider alg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); CryptographicKey key = alg.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(sharedKey)); return(Buffer.ToBytes( CryptographicEngine.Decrypt(key, CryptographicBuffer.CreateFromByteArray(cipherText), null))); }
public static string GenerateHash(string input, string key) { MacAlgorithmProvider mac = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1); IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); CryptographicKey cryptoKey = mac.CreateKey(keyMaterial); IBuffer hash = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8)); return(CryptographicBuffer.EncodeToBase64String(hash)); }
public static byte[] buildChatMessageBytes(string messageToSend, CryptographicKey encryptionKey = null) { JObject updateObj = new JObject(); updateObj.Add("updateType", "chat"); updateObj.Add("message", messageToSend); byte[] messageBytes = MessageBuilder.buildMessageBytes(updateObj, encryptionKey); return(messageBytes); //MessageBuilder.buildMessageBytes(updateObj, encryptionKey); }
public static byte[] buildOnlineStatusUpdateBytes(bool myOnlineStatus, CryptographicKey encryptionKey = null) { JObject updateObj = new JObject(); updateObj.Add("updateType", "onlineStatus"); updateObj.Add("onlineStatus", JsonConvert.SerializeObject(myOnlineStatus)); updateObj.Add("sessionID", AppServices.localSessionId); return(MessageBuilder.buildMessageBytes(updateObj, encryptionKey)); }
public static byte[] Encrypt(string Data, byte[] PublicKey) { CryptographicKey key = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1).ImportPublicKey(PublicKey.AsBuffer(), CryptographicPublicKeyBlobType.Capi1PublicKey); byte[] Encrypted; CryptographicBuffer.CopyToByteArray(CryptographicEngine.Encrypt(key, CryptographicBuffer.ConvertStringToBinary(Data, BinaryStringEncoding.Utf8), null), out Encrypted); return(Encrypted); }
public static byte[] Decrypt(byte[] Data, byte[] PrivateKey) { CryptographicKey key = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1).ImportKeyPair(PrivateKey.AsBuffer(), CryptographicPrivateKeyBlobType.Capi1PrivateKey); byte[] PlainData; CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(key, Data.AsBuffer(), null), out PlainData); return(PlainData); }
//Initialize the new Crypto object (initialized only once per app startup) public async void initCrypto() { this.strAsymmetricAlgName = AsymmetricAlgorithmNames.RsaPkcs1; this.asymmetricKeyLength = 512; //Checks SecureChat's folder if a key pair already exists and set keyPairExists boolean Windows.Storage.StorageFolder localAppFolder = Windows.Storage.ApplicationData.Current.LocalFolder; string cryptoFilePrivate = "SecureChatPrivateKeys.sckey"; //STORED AS BYTE DATA string cryptoFilePublic = "SecureChatPublicKey.sckey"; //STORED AS TEXT DATA if ((await localAppFolder.TryGetItemAsync(cryptoFilePublic) != null) && (await localAppFolder.TryGetItemAsync(cryptoFilePrivate) != null)) { this.keyPairExists = true; } else { this.keyPairExists = false; } //Load Keys depending on keyPairExists value if (this.keyPairExists == true) { //DIRECT IBUFFER //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic); //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic); //FROM BYTE //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync("BytePubKey.sckey"); //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic); //Open Public Key File. Convert key from STRING to BYTE and then convert to IBUFFER StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic); String publicKeyStringVersion = await FileIO.ReadTextAsync(loadedCryptoFilePublic); this.publicKeyByteVersion = Convert.FromBase64String(publicKeyStringVersion); this.buffPublicKey = this.publicKeyByteVersion.AsBuffer(); //Open Private Key File StorageFile loadedCryptoFilePrivate = await localAppFolder.GetFileAsync(cryptoFilePrivate); this.buffPrivateKeyStorage = await FileIO.ReadBufferAsync(loadedCryptoFilePrivate); } else { //Generate new key pair CryptographicKey temp = this.CreateAsymmetricKeyPair(strAsymmetricAlgName, asymmetricKeyLength, out buffPublicKey, out buffPrivateKeyStorage); //Convert public key from IBUFFER type to BYTE type. Convert from BYTE type to STRING type WindowsRuntimeBufferExtensions.CopyTo(this.buffPublicKey, this.publicKeyByteVersion); string publicKeyStringVersion = Convert.ToBase64String(this.publicKeyByteVersion); //Store keys in appropriate files (Public as PLAIN TEXT, Private as IBUFFER) await FileIO.WriteTextAsync((await localAppFolder.CreateFileAsync(cryptoFilePublic)), publicKeyStringVersion); await FileIO.WriteBufferAsync((await localAppFolder.CreateFileAsync(cryptoFilePrivate)), this.buffPrivateKeyStorage); } }
public AesEnDecryption() { IBuffer key = Convert.FromBase64String(AES_Key).AsBuffer(); m_iv = Convert.FromBase64String(AES_IV).AsBuffer(); SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); m_key = provider.CreateSymmetricKey(key); }
/// <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(); IBuffer Secret = CryptographicBuffer.ConvertStringToBinary("Master key to derive from", BinaryStringEncoding.Utf8); UInt32 TargetSize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString()); KeyDerivationText.Text = ""; KeyDerivationParameters Params; if (algName.Contains("PBKDF2")) { // Password based key derivation function (PBKDF2). Params = KeyDerivationParameters.BuildForPbkdf2( CryptographicBuffer.GenerateRandom(16), // Salt 10000 // PBKDF2 Iteration Count ); } else if (algName.Contains("SP800_108")) { // SP800_108_CTR_HMAC key derivation function. Params = KeyDerivationParameters.BuildForSP800108( CryptographicBuffer.ConvertStringToBinary("Label", BinaryStringEncoding.Utf8), // Label CryptographicBuffer.DecodeFromHexString("303132333435363738") // Context ); } else if (algName.Contains("SP800_56A")) { Params = KeyDerivationParameters.BuildForSP80056a( CryptographicBuffer.ConvertStringToBinary("AlgorithmId", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("VParty", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("UParty", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("SubPubInfo", BinaryStringEncoding.Utf8), CryptographicBuffer.ConvertStringToBinary("SubPrivInfo", BinaryStringEncoding.Utf8) ); } else { KeyDerivationText.Text += " An invalid algorithm was specified.\n"; return; } // Create a KeyDerivationAlgorithmProvider object for the algorithm specified on input. KeyDerivationAlgorithmProvider Algorithm = KeyDerivationAlgorithmProvider.OpenAlgorithm(algName); KeyDerivationText.Text += "*** Sample Kdf Algorithm: " + Algorithm.AlgorithmName + "\n"; KeyDerivationText.Text += " Secrect Size: " + Secret.Length + "\n"; KeyDerivationText.Text += " Target Size: " + TargetSize + "\n"; // Create a key. CryptographicKey key = Algorithm.CreateKey(Secret); // Derive a key from the created key. IBuffer derived = CryptographicEngine.DeriveKeyMaterial(key, Params, TargetSize); KeyDerivationText.Text += " Derived " + derived.Length + " bytes\n"; KeyDerivationText.Text += " Derived: " + CryptographicBuffer.EncodeToHexString(derived) + "\n"; }