/// <summary> /// 对字符串依据指定的算法和密钥进行加密,如果使用 CBC 算法,还需要初始化向量 /// </summary> /// <param name="content">源字符串</param> /// <param name="strAlgName">加密算法</param> /// <param name="encoding">字符串编码方式</param> /// <param name="key">密钥</param> /// <param name="iniVec">CBC 初始化向量</param> /// <returns></returns> public static IBuffer CipherEncryption(string content, string strAlgName, BinaryStringEncoding encoding, CryptographicKey key, IBuffer iniVec = null) { // Create a buffer that contains the encoded message to be encrypted. IBuffer buffContent = CryptographicBuffer.ConvertStringToBinary(content, encoding); // Open a symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // Determine whether the message length is a multiple of the block length. // This is not necessary for PKCS #7 algorithms which automatically pad the // message to an appropriate length. if (!strAlgName.Contains("PKCS7")) { if ((buffContent.Length % objAlg.BlockLength) != 0) { throw new Exception("Message buffer length must be multiple of block length."); } } if (strAlgName.Contains("CBC") && iniVec == null) { throw new ArgumentException("Using CBC Encryption, initial vector must have value"); } // Encrypt the data and return. IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffContent, iniVec); return(buffEncrypt); }
public static string CipherDecryption( string strAlgName, IBuffer buffEncrypt, IBuffer iv, BinaryStringEncoding encoding, CryptographicKey key) { // Declare a buffer to contain the decrypted data. IBuffer buffDecrypted; // Open an symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // The input key must be securely shared between the sender of the encrypted message // and the recipient. The initialization vector must also be shared but does not // need to be shared in a secure manner. If the sender encodes a message string // to a buffer, the binary encoding method must also be shared with the recipient. buffDecrypted = CryptographicEngine.Decrypt(key, buffEncrypt, iv); // Convert the decrypted buffer to a string (for display). If the sender created the // original message buffer from a string, the sender must tell the recipient what // BinaryStringEncoding value was used. Here, BinaryStringEncoding.Utf8 is used to // convert the message to a buffer before encryption and to convert the decrypted // buffer back to the original plaintext. return(CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted)); }
public Encrypted(string algorithm, BinaryStringEncoding encoding, string value) { Algorithm = algorithm; Value = value; Encoding = encoding; Validate(); }
void CreateHMAC(String strMsg, String strAlgName, out IBuffer buffMsg, out CryptographicKey hmacKey, out IBuffer buffHMAC) { // Create a MacAlgorithmProvider object for the specified algorithm. MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(strAlgName); // Demonstrate how to retrieve the name of the algorithm used. String strNameUsed = objMacProv.AlgorithmName; // Create a buffer that contains the message to be signed. BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Create a key to be signed with the message. IBuffer buffKeyMaterial = CryptographicBuffer.GenerateRandom(objMacProv.MacLength); hmacKey = objMacProv.CreateKey(buffKeyMaterial); // Sign the key and message together. buffHMAC = CryptographicEngine.Sign(hmacKey, buffMsg); // Verify that the HMAC length is correct for the selected algorithm if (buffHMAC.Length != objMacProv.MacLength) { throw new Exception("Error computing digest"); } }
public async void ProtectData() { // Initialize function arguments. String strDescriptor = "LOCAL=user"; String strLoremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse elementum " + "ullamcorper eros, vitae gravida nunc consequat sollicitudin. Vivamus lacinia, " + "diam a molestie porttitor, sapien neque volutpat est, non suscipit leo dolor " + "sit amet nisl. Praesent tincidunt tincidunt quam ut pharetra. Sed tincidunt " + "sit amet nisl. Praesent tincidunt tincidunt quam ut pharetra. Sed tincidunt " + "porttitor massa, at convallis dolor dictum suscipit. Nullam vitae lectus in " + "lorem scelerisque convallis sed scelerisque orci. Praesent sed ligula vel erat " + "eleifend tempus. Nullam dignissim aliquet mauris a aliquet. Nulla augue justo, " + "posuere a consectetur ut, suscipit et sem. Proin eu libero ut felis tincidunt " + "interdum. Curabitur vulputate eros nec sapien elementum ut dapibus eros " + "dapibus. Suspendisse quis dui dolor, non imperdiet leo. In consequat, odio nec " + "aliquam tincidunt, magna enim ultrices massa, ac pharetra est urna at arcu. " + "Nunc suscipit, velit non interdum suscipit, lectus lectus auctor tortor, quis " + "ultrices orci felis in dolor. Etiam congue pretium libero eu vestibulum. " + "Mauris bibendum erat eleifend nibh consequat eu pharetra metus convallis. " + "Morbi sem eros, venenatis vel vestibulum consequat, hendrerit rhoncus purus."; BinaryStringEncoding encoding = BinaryStringEncoding.Utf16BE; // Encrypt the data as a stream. IBuffer buffProtected = await this.SampleDataProtectionStream( strDescriptor, strLoremIpsum, encoding); // Decrypt a data stream. String strUnprotected = await this.SampleDataUnprotectStream( buffProtected, encoding); }
/// <summary> /// 对字符串依据指定的算法和密钥进行加密,如果使用 CBC 算法,还需要初始化向量 /// </summary> /// <param name="content">源字符串</param> /// <param name="strAlgName">加密算法</param> /// <param name="encoding">字符串编码方式</param> /// <param name="key">密钥</param> /// <param name="iniVec">CBC 初始化向量</param> /// <returns></returns> public static IBuffer CipherEncryption(string content, string strAlgName, BinaryStringEncoding encoding, CryptographicKey key, IBuffer iniVec = null) { // Create a buffer that contains the encoded message to be encrypted. IBuffer buffContent = CryptographicBuffer.ConvertStringToBinary(content, encoding); // Open a symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // Determine whether the message length is a multiple of the block length. // This is not necessary for PKCS #7 algorithms which automatically pad the // message to an appropriate length. if (!strAlgName.Contains("PKCS7")) { if ((buffContent.Length % objAlg.BlockLength) != 0) { throw new Exception("Message buffer length must be multiple of block length."); } } if (strAlgName.Contains("CBC") && iniVec == null) { throw new ArgumentException("Using CBC Encryption, initial vector must have value"); } // Encrypt the data and return. IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffContent, iniVec); return buffEncrypt; }
/// <summary> /// Generates a signature using the specified signatureType /// </summary> /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param> /// <param name="consumerKey">The consumer key</param> /// <param name="consumerSecret">The consumer seceret</param> /// <param name="token">The token, if available. If not available pass null or an empty string</param> /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param> /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param> /// <param name="signatureType">The type of signature to use</param> /// <returns>A base64 string of the hash value</returns> public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) { normalizedUrl = null; normalizedRequestParameters = null; switch (signatureType) { case SignatureTypes.PLAINTEXT: return(Uri.EscapeDataString(string.Format("{0}&{1}", consumerSecret, tokenSecret))); case SignatureTypes.HMACSHA1: string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters); MacAlgorithmProvider hmacsha1 = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); //HMACSHA1 hmacsha1 = new HMACSHA1(); // Create a key to be signed with the message. BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; IBuffer buffKeyMaterial = CryptographicBuffer.ConvertStringToBinary(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)), encoding); CryptographicKey hmacKey = hmacsha1.CreateKey(buffKeyMaterial); return(GenerateSignatureUsingHash(signatureBase, hmacsha1, hmacKey)); case SignatureTypes.RSASHA1: throw new NotImplementedException(); default: throw new ArgumentException("Unknown signature type", "signatureType"); } }
public string Encrypt(string plainText) { if (string.IsNullOrEmpty(plainText)) { throw new ArgumentNullException("plainText"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("Key"); } if (string.IsNullOrEmpty(iv)) { throw new ArgumentNullException("IV"); } BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, encoding); CryptographicKey cryptoKey = alg.CreateSymmetricKey(keyBuffer); IBuffer ivBuffer = CryptographicBuffer.ConvertStringToBinary(iv, encoding); // Add padding so buffer length is multiple of 16 plainText = PadString(plainText); IBuffer inputBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, encoding); IBuffer encryptedBuffer = CryptographicEngine.Encrypt(cryptoKey, inputBuffer, ivBuffer); return(CryptographicBuffer.EncodeToHexString(encryptedBuffer)); }
/// <summary> /// Write a string terminated with a specific character /// </summary> /// <param name="writer">DataWriter to write to</param> /// <param name="encoding">The string encoding used</param> /// <param name="s">The string to write</param> /// <param name="terminator">The terminating character</param> protected void WTS(DataWriter writer, BinaryStringEncoding encoding, string s, string terminator) { Encoding enc = GeneralUtils.GetEncodingFromType(encoding); byte[] data = enc.GetBytes(s); byte[] term = enc.GetBytes(terminator); writer.Write(data); writer.Write(term); }
static Cryptographer() { _targetKeySize = 256; _encoding = BinaryStringEncoding.Utf16LE; _keyDerivationAlgorithmName = KeyDerivationAlgorithmNames.Pbkdf2Sha512; _iterationCount = 10000; _encryptionAlgorithmName = SymmetricAlgorithmNames.AesCbcPkcs7; }
public async Task <string> UnprotectDataAsync(string strProtect, BinaryStringEncoding encoding) { DataProtectionProvider provider = new DataProtectionProvider(); encoding = BinaryStringEncoding.Utf8; IBuffer buffProtect = CryptographicBuffer.ConvertStringToBinary(strProtect, encoding); IBuffer buffMsg = await provider.UnprotectAsync(buffProtect); return(CryptographicBuffer.ConvertBinaryToString(encoding, buffMsg)); }
/// <summary> /// Converts encoding to an encoding object /// </summary> /// <param name="encoding">The encoding type</param> /// <returns>The encoding</returns> public static Encoding GetEncodingFromType(BinaryStringEncoding encoding) { Encoding ret; switch (encoding) { case BinaryStringEncoding.ASCII: ret = new BinaryEncoding(); break; case BinaryStringEncoding.UTF16_BE: ret = new UnicodeEncoding(true, false); break; case BinaryStringEncoding.UTF16_LE: ret = new UnicodeEncoding(false, false); break; case BinaryStringEncoding.UTF32_BE: ret = new UTF32Encoding(true, false); break; case BinaryStringEncoding.UTF32_LE: ret = new UTF32Encoding(false, false); break; case BinaryStringEncoding.UTF8: ret = new UTF8Encoding(); break; case BinaryStringEncoding.UTF7: ret = new UTF7Encoding(); break; case BinaryStringEncoding.EBCDIC_US: ret = Encoding.GetEncoding(37); break; case BinaryStringEncoding.Latin1: ret = Encoding.GetEncoding(28591); break; case BinaryStringEncoding.ShiftJIS: ret = Encoding.GetEncoding(932); break; default: ret = Encoding.GetEncoding((int)encoding); break; } return(ret); }
public static async void ProtectExample() { // Initialize function arguments. String strMsg = "This is a message to be protected."; String strDescriptor = "LOCAL=user"; BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; // Protect a message to the local user. IBuffer buffProtected = await SampleProtectAsync(strMsg, strDescriptor, encoding); // Decrypt the previously protected message. String strDecrypted = await SampleUnprotectData(buffProtected, encoding); }
private async Task <IBuffer> SampleDataProtectionStream( String descriptor, String strMsg, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(descriptor); // Convert the input string to a buffer. IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Create a random access stream to contain the plaintext message. InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream(); // Create a random access stream to contain the encrypted message. InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream(); // Retrieve an IOutputStream object and fill it with the input (plaintext) data. IOutputStream outputStream = inputData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(buffMsg); await writer.StoreAsync(); await outputStream.FlushAsync(); // Retrieve an IInputStream object from which you can read the input data. IInputStream source = inputData.GetInputStreamAt(0); // Retrieve an IOutputStream object and fill it with encrypted data. IOutputStream dest = protectedData.GetOutputStreamAt(0); await Provider.ProtectStreamAsync(source, dest); await dest.FlushAsync(); //Verify that the protected data does not match the original DataReader reader1 = new DataReader(inputData.GetInputStreamAt(0)); DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0)); await reader1.LoadAsync((uint)inputData.Size); await reader2.LoadAsync((uint)protectedData.Size); IBuffer buffOriginalData = reader1.ReadBuffer((uint)inputData.Size); IBuffer buffProtectedData = reader2.ReadBuffer((uint)protectedData.Size); if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData)) { throw new Exception("ProtectStreamAsync returned unprotected data"); } // Return the encrypted data. return(buffProtectedData); }
public async Task<string> Decrypt(IBuffer buffProtected, BinaryStringEncoding encoding) { try { // Create a DataProtectionProvider object. DataProtectionProvider Provider = new DataProtectionProvider(); // Create a random access stream to contain the encrypted message. InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream(); // Create a random access stream to contain the decrypted data. InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream(); // Retrieve an IOutputStream object and fill it with the input (encrypted) data. IOutputStream outputStream = inputData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(buffProtected); await writer.StoreAsync(); await outputStream.FlushAsync(); // Retrieve an IInputStream object from which you can read the input (encrypted) data. IInputStream source = inputData.GetInputStreamAt(0); // Retrieve an IOutputStream object and fill it with decrypted data. IOutputStream dest = unprotectedData.GetOutputStreamAt(0); await Provider.UnprotectStreamAsync(source, dest); await dest.FlushAsync(); // Write the decrypted data to an IBuffer object. DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0)); await reader2.LoadAsync((uint)unprotectedData.Size); IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size); // Convert the IBuffer object to a string using the same encoding that was // used previously to conver the plaintext string (before encryption) to an // IBuffer object. String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData); // Return the decrypted data. return strUnprotected; } catch (Exception ex) { App.Telemetry.TrackException(ex); return ""; } }
public static async Task <String> SampleUnprotectData(IBuffer buffProtected, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object. DataProtectionProvider Provider = new DataProtectionProvider(); // 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); }
private static async Task <String> UnprotectAsync( IBuffer buffProtected, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { // Create a DataProtectionProvider object. var provider = new DataProtectionProvider(); // Decrypt the protected message specified on input. var unprotectedBuffer = 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. return(CryptographicBuffer.ConvertBinaryToString(encoding, unprotectedBuffer)); }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="data"></param> /// <returns></returns> #if NETFX_CORE public static String GenerateSignatureUsingHash(String key, String data) { MacAlgorithmProvider hash = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1); BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; var dataBuffer = CryptographicBuffer.ConvertStringToBinary(data, encoding); IBuffer buffKeyMaterial = CryptographicBuffer.GenerateRandom(hash.MacLength); var hmacKey = hash.CreateKey(OAuth1Client.GenerateSignatureEncoding.GetBytes(key).AsBuffer()); var hashBytes = CryptographicEngine.Sign(hmacKey, dataBuffer); // Verify that the HMAC length is correct for the selected algorithm if (hashBytes.Length != hash.MacLength) { throw new Exception("Error computing digest"); } return(Convert.ToBase64String(hashBytes.ToArray())); }
/// <summary> /// Read a string of a fixed length /// </summary> /// <param name="reader">DataReader to read from</param> /// <param name="encoding">The string encoding used</param> /// <param name="length">The length of the string to read</param> /// <returns>The string read from the stream</returns> protected string FixS(DataReader reader, BinaryStringEncoding encoding, int length, int adjustment) { StringBuilder builder = new StringBuilder(); int i = 0; int len = length + adjustment; Encoding enc = GeneralUtils.GetEncodingFromType(encoding); while (i < len) { builder.Append(reader.ReadChar(enc)); ++i; } return(builder.ToString()); }
/// <summary> /// Este método decodifica un string en base64 con las características de padding especiales. /// </summary> /// <param name="b64String">cadena con los datos cifrados y con el padding definido</param> /// <param name="keyString">clave de descifrado</param> /// <returns></returns> public static byte[] decriptSpecialDES(string b64String, string keyString) { byte[] returnData = null; string sPadding = b64String.Substring(0, 2); byte[] encoded = Convert.FromBase64String(b64String.Substring(2)); int padding = 0; bool intConv = int.TryParse(sPadding.Substring(0, 1), out padding); if (!intConv) { return(returnData); } //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(encoded); //ciframos IBuffer cipherTextBuffered = CryptographicEngine.Decrypt(cryptographicKey, dataBuffer, null); //Se prepara el contenedor del mensaje cifrado byte[] cipherText = new byte[cipherTextBuffered.Length]; //Se copia el contenido CryptographicBuffer.CopyToByteArray(cipherTextBuffered, out cipherText); returnData = new byte[cipherText.Length - 8 - padding]; for (int i = 0; i < cipherText.Length - 8 - padding; i++) { returnData[i] = cipherText[i]; } return(returnData); }
public static async Task <String> SampleProtectAsync( String strMsg, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider provider = new DataProtectionProvider(strDescriptor); // Encode the plaintext input message to a buffer. IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Encrypt the message. IBuffer buffProtected = await provider.ProtectAsync(buffMsg); // Execution of the SampleProtectAsync function resumes here // after the awaited task (Provider.ProtectAsync) completes. return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16BE, buffProtected)); }
public async Task<IBuffer> Encrypt(string descriptor, string strMsg, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(descriptor); // Convert the input string to a buffer. IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Create a random access stream to contain the plaintext message. InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream(); // Create a random access stream to contain the encrypted message. InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream(); // Retrieve an IOutputStream object and fill it with the input (plaintext) data. IOutputStream outputStream = inputData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(buffMsg); await writer.StoreAsync(); await outputStream.FlushAsync(); // Retrieve an IInputStream object from which you can read the input data. IInputStream source = inputData.GetInputStreamAt(0); // Retrieve an IOutputStream object and fill it with encrypted data. IOutputStream dest = protectedData.GetOutputStreamAt(0); await Provider.ProtectStreamAsync(source, dest); await dest.FlushAsync(); //Verify that the protected data does not match the original DataReader reader1 = new DataReader(inputData.GetInputStreamAt(0)); DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0)); await reader1.LoadAsync((uint)inputData.Size); await reader2.LoadAsync((uint)protectedData.Size); IBuffer buffOriginalData = reader1.ReadBuffer((uint)inputData.Size); IBuffer buffProtectedData = reader2.ReadBuffer((uint)protectedData.Size); if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData)) { throw new Exception("ProtectStreamAsync returned unprotected data"); } // Return the encrypted data. return buffProtectedData; }
private async Task <String> SampleDataUnprotectStream( IBuffer buffProtected, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object. DataProtectionProvider Provider = new DataProtectionProvider(); // Create a random access stream to contain the encrypted message. InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream(); // Create a random access stream to contain the decrypted data. InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream(); // Retrieve an IOutputStream object and fill it with the input (encrypted) data. IOutputStream outputStream = inputData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(buffProtected); await writer.StoreAsync(); await outputStream.FlushAsync(); // Retrieve an IInputStream object from which you can read the input (encrypted) data. IInputStream source = inputData.GetInputStreamAt(0); // Retrieve an IOutputStream object and fill it with decrypted data. IOutputStream dest = unprotectedData.GetOutputStreamAt(0); await Provider.UnprotectStreamAsync(source, dest); await dest.FlushAsync(); // Write the decrypted data to an IBuffer object. DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0)); await reader2.LoadAsync((uint)unprotectedData.Size); IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size); // Convert the IBuffer object to a string using the same encoding that was // used previously to conver the plaintext string (before encryption) to an // IBuffer object. String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData); // Return the decrypted data. return(strUnprotected); }
public static IBuffer CipherEncryption( string strMsg, string strAlgName, out BinaryStringEncoding encoding, out IBuffer iv, out CryptographicKey key, uint keyLength = 128) { iv = null; // Initialize the initialization vector because some type encryptions do not need it. encoding = BinaryStringEncoding.Utf8; IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Open a symmetric algorithm provider for the specified algorithm. var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // Determine whether the message length is a multiple of the block length. // This is not necessary for PKCS #7 algorithms which automatically pad the // message to an appropriate length. if (!strAlgName.Contains("PKCS7")) { if ((buffMsg.Length % objAlg.BlockLength) != 0) { throw new Exception("Message buffer length must be multiple of block length."); } } // Create a symmetric key. // IBuffer keyMaterial = CryptographicBuffer.GenerateRandom(keyLength); // drop it. IBuffer keyMaterial = CryptographicBuffer.CreateFromByteArray(CollForKeyAndIv); key = objAlg.CreateSymmetricKey(keyMaterial); // CBC algorithms require an initialization vector. Here, a random number is used for the vector. if (strAlgName.Contains("CBC")) { //iv = CryptographicBuffer.GenerateRandom(objAlg.BlockLength); // drop it. iv = CryptographicBuffer.CreateFromByteArray(CollForKeyAndIv); } // Encrypt the data and return. IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffMsg, iv); return(buffEncrypt); }
public async static Task <string> ProtectAsync(String msg) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(strDescriptor); // Encode the plaintext input message to a buffer. BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(msg, encoding); // Encrypt the message. IBuffer buffProtected = await Provider.ProtectAsync(buffMsg); // Execution of the SampleProtectAsync function resumes here // after the awaited task (Provider.ProtectAsync) completes. string s = CryptographicBuffer.EncodeToHexString(buffProtected); return(s); }
public async Task<String> SampleUnprotectData( IBuffer buffProtected, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object. DataProtectionProvider Provider = new DataProtectionProvider(); // 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; }
private static async Task <IBuffer> ProtectAsync( String strMsg, String strDescriptor, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { // Create a DataProtectionProvider object for the specified descriptor. var provider = new DataProtectionProvider(strDescriptor); // Encode the plaintext input message to a buffer. encoding = BinaryStringEncoding.Utf8; var buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Encrypt the message. var protectedBuffer = await provider.ProtectAsync(buffMsg); // Execution of the SampleProtectAsync function resumes here // after the awaited task (Provider.ProtectAsync) completes. return(protectedBuffer); }
public async Task<IBuffer> SampleProtectAsync( String strMsg, String strDescriptor, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(strDescriptor); // Encode the plaintext input message to a buffer. encoding = BinaryStringEncoding.Utf8; IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Encrypt the message. IBuffer buffProtected = await Provider.ProtectAsync(buffMsg); // Execution of the SampleProtectAsync function resumes here // after the awaited task (Provider.ProtectAsync) completes. return buffProtected; }
public void EncryptTest() { string strMsg = string.Empty; // Message string string strAlgName = string.Empty; // Algorithm name uint keyLength = 0; // Length of key BinaryStringEncoding encoding = BinaryStringEncoding.Utf8; // Binary encoding type strAlgName = SymmetricAlgorithmNames.AesCbc; keyLength = 32; CryptographicKey key = CryptoHelper.GenerateKey(strAlgName, keyLength); // Symmetric Key strMsg = "1234567812345678"; IBuffer buffEncrypted = CryptoHelper.CipherEncryption(strMsg, strAlgName, encoding, key); var actual = CryptoHelper.CipherDecryption(strAlgName, buffEncrypted, encoding, key); Assert.AreEqual(strMsg, actual); }
/// <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 static async Task<string> ComputeMd5(IInputStream stream, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { var hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); var hash = hashAlgorithmProvider.CreateHash(); uint size = 1024*64; var buffer = new Buffer(size); while (true) { var x = await stream.ReadAsync(buffer, size, InputStreamOptions.Partial); if (x.Length < 1) { break; } hash.Append(x); } var result = hash.GetValueAndReset(); var hex = CryptographicBuffer.EncodeToHexString(result); return hex; }
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); }
// 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; }
/// <summary> /// 加密字符串 /// </summary> public static IBuffer SampleCipherEncryption(String strMsg, string keyStr, BinaryStringEncoding encoding) { IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); return SampleCipherEncryption(buffMsg, keyStr, encoding); }
/// <summary> /// 加密buffer内容 /// </summary> /// <param name="original"></param> /// <param name="keyStr"></param> /// <param name="encoding"></param> /// <returns></returns> public static IBuffer SampleCipherEncryption(IBuffer original, string keyStr, BinaryStringEncoding encoding) { // Initialize the initialization vector. // Initialize the binary encoding value. //var encoding = BinaryStringEncoding.Utf8; // Create a buffer that contains the encoded message to be encrypted. String strAlgName = SymmetricAlgorithmNames.Rc2EcbPkcs7; // Open a symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // Determine whether the message length is a multiple of the block length. // This is not necessary for PKCS #7 algorithms which automatically pad the // message to an appropriate length. if (!strAlgName.Contains("PKCS7")) { if ((original.Length % objAlg.BlockLength) != 0) { throw new Exception("Message buffer length must be multiple of block length."); } } // Create a symmetric key. var keyMaterial = CryptographicBuffer.ConvertStringToBinary(keyStr, encoding); var key = objAlg.CreateSymmetricKey(keyMaterial); // CBC algorithms require an initialization vector. Here, a random // number is used for the vector. //if (strAlgName.Contains("CBC")) //{ // iv = CryptographicBuffer.GenerateRandom(objAlg.BlockLength); //} // Encrypt the data and return. IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, original, null); return buffEncrypt; }
private static string ComputeHash(string str, string hashAlgorithmName, BinaryStringEncoding encoding) { var buff = CryptographicBuffer.ConvertStringToBinary(str, encoding); var hashed = ComputeHashWithBuffer(buff, hashAlgorithmName); return CryptographicBuffer.EncodeToHexString(hashed); }
/// <summary> /// 对一段 Buffer 根据指定的算法和密钥解密,如果使用 CBC 算法,还需要初始化向量 /// </summary> /// <param name="strAlgName">算法</param> /// <param name="buffEncrypt">加密缓冲区</param> /// <param name="encoding">编码方式</param> /// <param name="key">密钥</param> /// /// <param name="iniVec">初始化向量</param> /// <returns></returns> public static string CipherDecryption(string strAlgName, IBuffer buffEncrypt, BinaryStringEncoding encoding, CryptographicKey key, IBuffer iniVec = null) { // 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, iniVec); // Convert the decrypted buffer to a string (for display). If the sender created the // original message buffer from a string, the sender must tell the recipient what // BinaryStringEncoding value was used. Here, BinaryStringEncoding.Utf8 is used to // convert the message to a buffer before encryption and to convert the decrypted // buffer back to the original plaintext. return ToString(encoding, buffDecrypted); }
public static Windows.Storage.Streams.IBuffer ConvertStringToBinary(string value, BinaryStringEncoding encoding) => throw null;
public static string ToString(BinaryStringEncoding encoding, IBuffer buff) { return CryptographicBuffer.ConvertBinaryToString(encoding, buff); }
public static string ComputeSha256(string str, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { return ComputeHash(str, HashAlgorithmNames.Sha256, encoding); }
public static IBuffer ConvertToBuffer(this string stringToConvert, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { return(CryptographicBuffer.ConvertStringToBinary(stringToConvert, encoding)); }
public static string ToString(BinaryStringEncoding encoding, IBuffer buff) { return(CryptographicBuffer.ConvertBinaryToString(encoding, buff)); }
/// <summary> /// 解密字符串 /// </summary> /// <param name="strAlgName"></param> /// <param name="buffEncrypt"></param> /// <param name="iv"></param> /// <param name="encoding"></param> /// <param name="key"></param> /// <returns></returns> public static IBuffer SampleCipherDecryption(IBuffer buffEncrypt, string keyStr, BinaryStringEncoding encoding) { // Declare a buffer to contain the decrypted data. IBuffer buffDecrypted; String strAlgName = SymmetricAlgorithmNames.Rc2EcbPkcs7; // Open an symmetric algorithm provider for the specified algorithm. SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); var keyMaterial = CryptographicBuffer.ConvertStringToBinary(keyStr, encoding); var key = objAlg.CreateSymmetricKey(keyMaterial); // 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, null); // 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); return buffDecrypted; }