/// <summary> /// Encypts a string using a key signed by a KeyCredential. /// </summary> /// <param name="strClearText">Text to encrypt.</param> /// <param name="rResult">KeyCredential object used to sign a key to encrypt the text.</param> /// <returns>Encrypted text.</returns> internal static async Task <string> Encrypt(ProtectedString ps, KeyCredentialRetrievalResult rResult) { Assembly assembly = Assembly.GetExecutingAssembly(); var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0]; var id = attribute.Value; // Any text can be used, it will be signed with the KeyCredential to encrypt the string IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(id, encoding); // converted to an IBuffer // The actual Signing of the string KeyCredentialOperationResult opResult = await rResult.Credential.RequestSignAsync(buffMsg); IBuffer signedData = opResult.Result; // Creation of the key with the signed string SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); CryptographicKey myKey = provider.CreateSymmetricKey(signedData); // Encryption of the data using the key created (mKey) var pb = ps.ReadUtf8(); IBuffer buffClear = CryptographicBuffer.CreateFromByteArray(pb); IBuffer buffProtected = CryptographicEngine.Encrypt(myKey, buffClear, null); buffClear = null; MemUtil.ZeroByteArray(pb); return(CryptographicBuffer.EncodeToBase64String(buffProtected)); }
private byte[] getCiphertext(byte[] key, byte[] message) { try { SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // TODO: PKCS5 padding IBuffer buffKey = CryptographicBuffer.CreateFromByteArray(key); CryptographicKey ckey = objAlg.CreateSymmetricKey(buffKey); IBuffer buffPlaintext = CryptographicBuffer.CreateFromByteArray(message); byte[] iv = BitConverter.GetBytes(CryptographicBuffer.GenerateRandomNumber()); IBuffer buffIV = CryptographicBuffer.CreateFromByteArray(iv); IBuffer buffEncrypt = CryptographicEngine.Encrypt(ckey, buffPlaintext, buffIV); byte[] ret; CryptographicBuffer.CopyToByteArray(buffEncrypt, out ret); /*Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); * cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));*/ return(Util.join(iv, ret)); } catch (/*NoSuchAlgorithmException | NoSuchPaddingException | java.security.InvalidKeyException | IllegalBlockSizeException | BadPaddingException*/ Exception e) { throw new Exception(e.Message); } }
internal static string EncryptThisData(string input, string pass) { SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); CryptographicKey AES; HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); CryptographicHash Hash_AES = HAP.CreateHash(); string encrypted = ""; try { byte[] hash = new byte[32]; Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass))); byte[] temp; CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp); Array.Copy(temp, 0, hash, 0, 16); Array.Copy(temp, 0, hash, 15, 16); AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash)); IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(input)); encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null)); return(encrypted); } catch (Exception ex) { Debug.WriteLine(ex); return(null); } }
/// <summary> /// Encrypt value using password. /// </summary> /// <param name="value">Value to encrypt.</param> /// <param name="key">Key that is used for encryption.</param> /// <returns>A buffer with the encrypted data is returned.</returns> public IBuffer Encrypt(string value, 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 an Aes256 with CBC and Pkcs7 var aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); CryptographicKey aesKey = aesProvider.CreateSymmetricKey(keyMaterial); // Create a random IV so the password can be used more than once. IBuffer iv = CryptographicBuffer.GenerateRandom(aesProvider.BlockLength); // Encrypt value. var data = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8); IBuffer encrypted = CryptographicEngine.Encrypt(aesKey, data, iv); // Insert random generated IV before encrypted message because it will be needed at decryption. IBuffer result = CryptographicBuffer.CreateFromByteArray(new byte[iv.Length + encrypted.Length]); iv.CopyTo(0, result, 0, iv.Length); encrypted.CopyTo(0, result, iv.Length, encrypted.Length); return(result); }
public Task <byte[]> AesEncryptAsync(byte[] data, byte[] iv, byte[] key) { var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7); var cryptoKey = provider.CreateSymmetricKey(key); return(Task.FromResult(CryptographicEngine.Encrypt(cryptoKey, data, iv))); }
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); }
/// <summary> /// Encrypt a string using dual encryption method. Returns an encrypted text. /// </summary> /// <param name="toEncrypt">String to be encrypted</param> /// <param name="key">Unique key for encryption/decryption</param>m> /// <returns>Returns encrypted string.</returns> public static string Encrypt(string toEncrypt, string key) { try { // Get the MD5 key hash (you can as well use the binary of the key string) var keyHash = GetMD5Hash(key); // Create a buffer that contains the encoded message to be encrypted. var toDecryptBuffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8); // Open a symmetric algorithm provider for the specified algorithm. var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); // Create a symmetric key. var symetricKey = aes.CreateSymmetricKey(keyHash); // The input key must be securely shared between the sender of the cryptic 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. var buffEncrypted = CryptographicEngine.Encrypt(symetricKey, toDecryptBuffer, null); // Convert the encrypted buffer to a string (for display). // We are using Base64 to convert bytes to string since you might get unmatched characters // in the encrypted buffer that we cannot convert to string with UTF8. var strEncrypted = CryptographicBuffer.EncodeToBase64String(buffEncrypted); return(strEncrypted); } catch (Exception ex) { // MetroEventSource.Log.Error(ex.Message); return(""); } }
/// <summary> /// Initializes a new instance of the <see cref="SecureString"/> class from a subarray of /// <see cref="char"/> objects. /// </summary> /// <param name="value">A pointer to an array of System.Char objects.</param> /// <param name="length">The number of elements of value to include in the new instance.</param> public unsafe SecureString(char *value, int length) { this.Length = length; this.initialisationVector = Encoding.UTF8.GetBytes(CryptoUtils.BrewPassword(42)).GetBytes(16); byte[] dataCopy = new byte[length]; var gc = GCHandle.Alloc(dataCopy, GCHandleType.Pinned); for (int i = 0; i < dataCopy.Length; i++) { dataCopy[i] = (byte)*(value + i); } // We cannot use our Aes implemtation in here because we will cause a cycling // dependency... And that will lead to a StackOverflow var passPhrase = Encoding.UTF8.GetBytes(SystemInfo.HardwareIdentifier.GetHash(HashAlgorithms.Sha512)); var keyMaterial = CryptographicBuffer.CreateFromByteArray(passPhrase); var toDecryptBuffer = CryptographicBuffer.CreateFromByteArray(dataCopy); var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); var symetricKey = aes.CreateSymmetricKey(keyMaterial); var buffEncrypted = CryptographicEngine.Encrypt(symetricKey, dataCopy.AsBuffer(), initialisationVector.AsBuffer()); CryptographicBuffer.CopyToByteArray(buffEncrypted, out data); gc.FillWithRandomValues(dataCopy.Length); }
public static string Encrypt(string plainText) { //Chuyen password sang IBuffer theo dinh dang Utf8 IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8); //Chuyen salt theo dinh dang Utf8 IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8); //Chuyen chuoi can ma hoa sang IBuffer theo dinh dang Utf8 IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8); //Khai bao thuat toan bam KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); //Tao param key gia tri salt voi so lan lap 1000 theo thuat toan PBKDF2_SHA1 KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000); //Tao KeyOriginal de ma hoa tu mat khau CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); //Tao KeyMaterial de ma hoa tu keyOriginal va key cua Salt voi kich thuoc 32 byte IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); //Tao saltMaterial de ma hoa tu derivedPwKey va key cua Salt voi kich thuoc la 16 byte IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 16); //Khai bao thuat toan ma hoa SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); //Tao key ma hoa tu keyMaterial CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial); //Ma hoa chuoi du lieu IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial); //Chuyen du lieu sau khi ma hoa sang dang chuoi return(CryptographicBuffer.EncodeToBase64String(resultBuffer)); }
private async void EncryptButton_Click_1(object sender, RoutedEventArgs e) { var message = string.Empty; try { var result = await GetPassword(); var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("RC4"); var key = provider.CreateSymmetricKey(AsBuffer(result)); var encrypted = CryptographicEngine.Encrypt(key, AsBuffer(BigTextBox.Text), null); _encrypted = encrypted.ToArray(); BigTextBlock.Text = CryptographicBuffer.EncodeToBase64String(encrypted); DecryptButton.IsEnabled = true; } catch (Exception ex) { message = ex.Message; } if (!string.IsNullOrEmpty(message)) { await SimpleDialog(message); } }
public static string Encrypt(string toEncrypt, byte[] key = null) { if (toEncrypt == "") { return(""); } if (key == null || key.Length == 0) { key = Default; } var keyHash = key.AsBuffer(); // Create a buffer that contains the encoded message to be encrypted. var toEncryptBuffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8); // Open a symmetric algorithm provider for the specified algorithm. var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesEcbPkcs7); // Create a symmetric key. var symetricKey = aes.CreateSymmetricKey(keyHash); // The input key must be securely shared between the sender of the cryptic 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. var buffEncrypted = CryptographicEngine.Encrypt(symetricKey, toEncryptBuffer, null); // We are using Base64 to convert bytes to string since you might get unmatched characters // in the encrypted buffer that we cannot convert to string with UTF8. var strEncrypted = CryptographicBuffer.EncodeToBase64String(buffEncrypted); return(strEncrypted); }
//public static long GetTimeToUNIX(TimeSpan ts) //{ // return (long)(ts-(new DateTime(1970,1,1,0,0,0))). //} public static string ACAESENCODE(string value, string key) { var buffKey = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); byte[] vds = Encoding.UTF8.GetBytes(value); int k = (int)aes.BlockLength; int vs = vds.Length; int i = vs; if (vs % k != 0) { i = vs + (k - vs % k); } var data = new byte[i]; Array.Copy(vds, 0, data, 0, vds.Length); var toDecryptBuffer = CryptographicBuffer.CreateFromByteArray(data); var symmetricKey = aes.CreateSymmetricKey(buffKey); var buffEncrypted = CryptographicEngine.Encrypt(symmetricKey, toDecryptBuffer, null); var str = CryptographicBuffer.EncodeToBase64String(buffEncrypted); return(str); }
private static readonly string ENC_ALG = SymmetricAlgorithmNames.AesCbcPkcs7; // crypto alg. to use for enc/dec public static byte[] encrypt(byte[] input, byte[] key) { var buffer = CryptographicBuffer.CreateFromByteArray(input); var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(ENC_ALG); var symmetricKey = aes.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(key)); // generate a random initialization vector // var ivBuffer = CryptographicBuffer.GenerateRandom(IV_LENGTH); var encryptedBuffer = CryptographicEngine.Encrypt(symmetricKey, buffer, null); byte[] encryptedByteArr = new byte[encryptedBuffer.Length]; /* * byte[] iv = new byte[IV_LENGTH]; * CryptographicBuffer.CopyToByteArray(ivBuffer, out iv); */ CryptographicBuffer.CopyToByteArray(encryptedBuffer, out encryptedByteArr); /* * byte[] outputBuffer = new byte[iv.Length + encryptedByteArr.Length]; * Buffer.BlockCopy(iv, 0, outputBuffer, 0, iv.Length); * Buffer.BlockCopy(encryptedByteArr, 0, outputBuffer, iv.Length, encryptedByteArr.Length); */ return(encryptedByteArr); }
/// <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(this string str) { if (string.IsNullOrWhiteSpace(str)) { return(""); } var key = StringWithAES.GetHardwareId().Remove(32); SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7); CryptographicKey AES; HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); CryptographicHash Hash_AES = HAP.CreateHash(); var hash = new byte[32]; Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(key))); byte[] temp; CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp); Array.Copy(temp, 0, hash, 0, 16); Array.Copy(temp, 0, hash, 15, 16); AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash)); IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(str)); return(CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null))); }
/// <summary> /// Encrypts data /// </summary> /// <param name="publicKey">The public key to use to encrypt the data</param> /// <param name="data">The data to encrypt</param> /// <returns>The ecrypted data</returns> /// <exception cref="ArgumentNullException"><paramref name="publicKey"/> is null</exception> /// <exception cref="ArgumentNullException"><paramref name="data"/> is null</exception> public static byte[] Encrypt(string publicKey, byte[] data) { if (publicKey == null) { throw new ArgumentNullException(nameof(publicKey)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } #if WINDOWS_UWP var keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey); var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); var key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Capi1PublicKey); var plainBuffer = CryptographicBuffer.CreateFromByteArray(data); var encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null); byte[] encryptedBytes; CryptographicBuffer.CopyToByteArray(encryptedBuffer, out encryptedBytes); return(encryptedBytes); #else var cspParams = new CspParameters { ProviderType = 1 /* PROV_RSA_FULL */ }; var rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey)); return(rsaProvider.Encrypt(data, false)); #endif }
private static IBuffer AESEncrypt(IBuffer plainText, IBuffer IV, IBuffer keyBuffer) { var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); var key = provider.CreateSymmetricKey(keyBuffer); return(CryptographicEngine.Encrypt(key, plainText, IV)); }
private static async Task <string> EncryptedPassword(string passWord) { string base64String; try { 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); string url = "https://passport.bilibili.com/api/oauth2/getKey"; string content = $"appkey={ApiHelper._appKey}&mobi_app=android&platform=android&ts={ApiHelper.GetTimeSpan}"; content += "&sign=" + ApiHelper.GetSign(content); string stringAsync = await WebClientClass.PostResults(new Uri(url), content); JObject jObjects = JObject.Parse(stringAsync); string str = jObjects["data"]["hash"].ToString(); string str1 = jObjects["data"]["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) { base64String = passWord; } return(base64String); }
public string EncryptObject(object objectToEncrypt) { if (!_initialized) { throw new Exception("Crypt engine is not initialized."); } string result = null; byte[] iv = GetRandomBytes(cryptoBlockSizeInBytes); if (objectToEncrypt != null) { byte[] bytesToEncrypt = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objectToEncrypt)); var aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7"); CryptographicKey aesKey = aesProvider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(_keyBytes)); IBuffer aesIv = CryptographicBuffer.CreateFromByteArray(iv); IBuffer decrypted = CryptographicBuffer.CreateFromByteArray(bytesToEncrypt); IBuffer encrypted = CryptographicEngine.Encrypt(aesKey, decrypted, aesIv); byte[] encryptedBytes; using (var dr = DataReader.FromBuffer(encrypted)) { encryptedBytes = new byte[dr.UnconsumedBufferLength]; dr.ReadBytes(encryptedBytes); } result = Convert.ToBase64String(JoinByteArrays(iv, encryptedBytes)); } result = result ?? Convert.ToBase64String(iv); return(result); }
public byte[] Encrypt(byte[] input) { IBuffer bufferMsg = CryptographicBuffer.ConvertStringToBinary(Encoding.ASCII.GetString(input), BinaryStringEncoding.Utf8); IBuffer bufferEncrypt = CryptographicEngine.Encrypt(m_key, bufferMsg, m_iv); return(bufferEncrypt.ToArray()); }
public static string Encrypt(String strMsg) { IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); IBuffer buffEncrypt = CryptographicEngine.Encrypt(Key, buffMsg, IV.AsBuffer()); return(CryptographicBuffer.EncodeToBase64String(buffEncrypt)); }
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 Task <byte[]> RsaEncryptAsync(byte[] data, byte[] publicKey, CryptoHashAlgorithm algorithm) { var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(ToAsymmetricAlgorithm(algorithm)); var cryptoKey = provider.ImportPublicKey(publicKey, CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo); return(Task.FromResult(CryptographicEngine.Encrypt(cryptoKey, data))); }
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)); }
/// <summary> /// Computes PKCS5 for the message /// </summary> /// <param name="message">plaintext</param> /// <returns>PKCS5 of the message</returns> public static byte[] aesCbcPkcs5(byte[] message, byte[] key, byte[] iv) { ISymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7); // PKCS5 ICryptographicKey ckey = objAlg.CreateSymmetricKey(key); byte [] result = CryptographicEngine.Encrypt(ckey, message, iv); return(result); }
private string Encrypt(string plainText) { var key = GetAppCryptoKey(); var plain = Encoding.UTF8.GetBytes(plainText); var encrypted = CryptographicEngine.Encrypt(key, plain); return(Convert.ToBase64String(encrypted)); }
private byte[] AesEcbEncrypt(byte[] data, byte[] key) { SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); var symetricKey = aes.CreateSymmetricKey(key.AsBuffer()); var buffEncrypted = CryptographicEngine.Encrypt(symetricKey, data.AsBuffer(), null); return(buffEncrypted.ToArray()); }
//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); }
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); }
private static byte[] AesEnc(byte[] sharedKey, byte[] plainText) { SymmetricKeyAlgorithmProvider alg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb); CryptographicKey key = alg.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(sharedKey)); return(Buffer.ToBytes( CryptographicEngine.Encrypt(key, CryptographicBuffer.CreateFromByteArray(plainText), null))); }