/// <summary> /// Initializes a new instance of the <see cref="CryptographicKey" /> class. /// </summary> /// <param name="key">The WinRT cryptographic key.</param> /// <param name="canExportPrivateKey"> /// A value indicating whether <see cref="Export(CryptographicPrivateKeyBlobType)"/> /// can be expected to work. /// </param> internal CryptographicKey(Platform.CryptographicKey key, bool canExportPrivateKey) { Requires.NotNull(key, "key"); this.key = key; this.canExportPrivateKey = canExportPrivateKey; }
/// <summary> /// Дешифрования текст /// </summary> /// <param name="SourceText">Исходный (шифрованный) текст</param> /// <param name="InputKey">Ключ шифрования</param> /// <param name="AlgorytmName">Имя алгоритма дешифрования</param> /// /// <returns>Расшифрованный (открытый) текст</returns> public string DecrypMode(string SourceText, string InputKey, string AlgorytmName, string IV, string KeySize) { SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorytmName); IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE); //CryptoKey = Algorithm.CreateSymmetricKey(keymaterial); KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms,Convert.ToUInt32(KeySize)/8); // string test= CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial); CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial); if (AlgorytmName.Contains("CBC")) { IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE); } // Set the data to encrypt. SourceTextBuffer = CryptographicBuffer.DecodeFromBase64String(SourceText); // Decrypt DecryptBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(CryptoKey, SourceTextBuffer, IVBuffer); DecryptTextOutput = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, DecryptBuffer);//Надо думать над реализацией Base64 return DecryptTextOutput; }
/// <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 OTP(string key) { MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1); IBuffer keyMaterial = CryptographicBuffer.CreateFromByteArray(key.ToBytesBase32()); cKey = provider.CreateKey(keyMaterial); }
public Aes128Pkcs7ReadStream(Stream parent, byte[] key, byte[] iv) { if (parent == null) throw new ArgumentNullException(nameof(parent)); if (key == null) throw new ArgumentNullException(nameof(key)); if (!parent.CanRead) throw new ArgumentException("parent must be a readable stream"); _parent = parent; var algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc); var lastAlgorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); _blockLength = (int)lastAlgorithm.BlockLength; if (null != iv && iv.Length != _blockLength) throw new ArgumentOutOfRangeException(nameof(iv), "length must match the block length"); _encryptedBuffer = _encrypted.AsBuffer(); _encryptedBuffer.Length = 0; var keyBuffer = key.AsBuffer(); _key = algorithm.CreateSymmetricKey(keyBuffer); _lastKey = lastAlgorithm.CreateSymmetricKey(keyBuffer); _ivBuffer = CopyArray(iv).AsBuffer(); }
/// <summary> /// Encrypt using AES/ECB /// </summary> /// <param name="message">The message to encrypt</param> /// <param name="key">The key with which to encrypt</param> /// <returns>Encrypted data</returns> private static byte[] EncryptAes(byte[] message, CryptographicKey key) { int blockRoundedSize = ((message.Length + 15) / 16) * 16; byte[] paddedMessage = new byte[blockRoundedSize]; Array.Copy(message, paddedMessage, message.Length); IBuffer encrypted; IBuffer iv = null; IBuffer data = CryptographicBuffer.CreateFromByteArray(paddedMessage); String algName = SymmetricAlgorithmNames.AesEcb; // Encrypt the data. try { encrypted = CryptographicEngine.Encrypt(key, data, iv); } catch (Exception) { Debug.WriteLine("An invalid key size was selected for the given algorithm.\n"); return null; } byte[] encryptedMsg = new byte[encrypted.Length]; CryptographicBuffer.CopyToByteArray(encrypted, out encryptedMsg); return encryptedMsg; }
/// <summary> /// Initializes a new instance of the <see cref="CryptographicKey" /> class. /// </summary> /// <param name="key">The WinRT cryptographic key.</param> /// <param name="symmetricAlgorithmProvider">The symmetric algorithm of the provider creating this key.</param> internal CryptographicKey(Platform.CryptographicKey key, SymmetricKeyAlgorithmProvider symmetricAlgorithmProvider) { Requires.NotNull(key, "key"); this.key = key; this.symmetricAlgorithmProvider = symmetricAlgorithmProvider; }
private void AsymmetricImportExport(CryptographicKey keyPair) { String algName = AlgorithmNames.SelectionBoxItem.ToString(); AsymmetricKeyAlgorithmProvider Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algName); // Export the public key. IBuffer blobOfPublicKey = keyPair.ExportPublicKey(); IBuffer blobOfKeyPair = keyPair.Export(); SignVerifyText.Text += " Key pair was successfully exported.\n"; // Import the public key. CryptographicKey keyPublic = Algorithm.ImportPublicKey(blobOfPublicKey); // Check the key size. if (keyPublic.KeySize != keyPair.KeySize) { SignVerifyText.Text += "ImportPublicKey failed! The imported key's size did not match the original's!"; return; } SignVerifyText.Text += " Public key was successfully imported.\n"; // Import the key pair. keyPair = Algorithm.ImportKeyPair(blobOfKeyPair); // Check the key size. if (keyPublic.KeySize != keyPair.KeySize) { SignVerifyText.Text += "ImportKeyPair failed! The imported key's size did not match the original's!"; return; } SignVerifyText.Text += " Key pair was successfully imported.\n"; }
/// <summary> /// Initializes a new instance of the <see cref="WinRTCryptographicKey" /> class. /// </summary> /// <param name="key">The WinRT cryptographic key.</param> /// <param name="canExportPrivateKey"> /// A value indicating whether <see cref="Export(CryptographicPrivateKeyBlobType)"/> /// can be expected to work. /// </param> internal WinRTCryptographicKey(Platform.CryptographicKey key, bool canExportPrivateKey) { Requires.NotNull(key, "key"); this.key = key; this.canExportPrivateKey = canExportPrivateKey; }
public static IBuffer Encrypt(IBuffer data, CryptographicKey key, out IBuffer iv, String AlgorithmName = null) { //declares var strAlgName = AlgorithmName != null ? AlgorithmName : DefaultAlgorithm; iv = null; // 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 ((data.Length % objAlg.BlockLength) != 0) throw new Exception("Message buffer length must be multiple of block length."); } // 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. return CryptographicEngine.Encrypt(key, data, iv); }
public static IBuffer EncryptString(String strMsg, CryptographicKey key, out IBuffer iv, String AlgorithmName = null) { // Create a buffer that contains the encoded message to be encrypted. var buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8); //encrypt return Encrypt(buffMsg, key, out iv, AlgorithmName: AlgorithmName); }
/// <summary> /// Signs digital content. For more information, see MACs, Hashes, and Signatures. /// </summary> /// <param name="key">Key used for signing.</param> /// <param name="data">Data to be signed.</param> /// <returns>Signed data.</returns> public static IBuffer Sign( CryptographicKey key, IBuffer data ) { if (key.Hash != null) { var signature = key.Hash.ComputeHash(data.ToArray()); return new WindowsRuntimeBuffer(signature); } throw new NotImplementedException(); }
/// <summary> /// Decrypt using AES /// </summary> /// <param name="encrypted">Data to decrypt</param> /// <param name="key">Key with which to decrypt</param> /// <returns>Decrypted data</returns> private static byte[] DecryptAes(byte[] encrypted, CryptographicKey key) { int blockRoundedSize = ((encrypted.Length + 15) / 16) * 16; byte[] paddedEncrypted = new byte[blockRoundedSize]; Array.Copy(encrypted, paddedEncrypted, encrypted.Length); IBuffer encryptedBuf = CryptographicBuffer.CreateFromByteArray(paddedEncrypted); IBuffer iv = null; IBuffer decryptedBuf = CryptographicEngine.Decrypt(key, encryptedBuf, iv); byte[] decrypted = new byte[decryptedBuf.Length]; CryptographicBuffer.CopyToByteArray(decryptedBuf, out decrypted); return decrypted; }
/// <summary> /// Helper function to compute a hash value /// </summary> /// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param> /// <param name="data">The data to hash</param> /// <returns>a Base64 string of the hash value</returns> private IBuffer ComputeHash(CryptographicKey hashAlgorithm, string data) { if (hashAlgorithm == null) { throw new ArgumentNullException("hashAlgorithm"); } if (string.IsNullOrEmpty(data)) { throw new ArgumentNullException("data"); } var signature = CryptographicEngine.Sign( hashAlgorithm, CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8)); return signature; }
/// <summary> /// Generate the signature value based on the given signature base and hash algorithm /// </summary> /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param> /// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param> /// <returns>A base64 string of the hash value</returns> public IBuffer GenerateSignatureUsingHash(string signatureBase, CryptographicKey hash) { return ComputeHash(hash, signatureBase); }
public static JObject decodeMessageBytes(byte[] update, CryptographicKey encryptionKey = null) { string dataString = System.Text.Encoding.UTF8.GetString(update, 0, update.Length); if (encryptionKey == null) return JObject.Parse(dataString); else return JObject.Parse(AppServices.DecryptString(dataString, encryptionKey)); //return new MessageBuilder(jsonObj["sender"].ToString(), jsonObj["message"].ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="WinRTCryptographicKey"/> class. /// </summary> /// <param name="platformKey">The WinRT key that this instance wraps.</param> internal WinRTCryptographicKey(Platform.Core.CryptographicKey platformKey) { Requires.NotNull(platformKey, nameof(platformKey)); this.platformKey = platformKey; }
//Converts JSON object into byte array object containing representing C# JSON object // with the sender name and message public static byte[] buildMessageBytes(JObject dataToGetBytes, CryptographicKey encryptionKey = null) { string objectString = dataToGetBytes.ToString(); if (encryptionKey == null) return System.Text.Encoding.UTF8.GetBytes(objectString); else return System.Text.Encoding.UTF8.GetBytes(AppServices.EncryptString(objectString, encryptionKey)); }
/// <summary> /// Initializes a new instance of the <see cref="CryptographicKey" /> class. /// </summary> /// <param name="key">The WinRT cryptographic key.</param> internal CryptographicKey(Platform.CryptographicKey key) { Requires.NotNull(key, "key"); this.key = key; }
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); }
// Decrypt data using the AES_ECB_PKCS7 Algorithim and the given key and return the raw data as a UTF8 encoded string. // the data passed in should be encrypted HEX encoded string that was encrypted using the passed in encryptionKey public static string DecryptString(string data, CryptographicKey encryptionKey) { // Create the algorithim, the key, and a buffer to store the string that we want to encrypt IBuffer dataBuff = CryptographicBuffer.DecodeFromHexString(data); // Decrypt the data and return it as a string IBuffer decryptedBuff = CryptographicEngine.Decrypt(encryptionKey, dataBuff, null); return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuff); }
public static IBuffer Decrypt(IBuffer encBuffer, CryptographicKey key, IBuffer iv, String AlgorithmName = null) { //declares var strAlgName = AlgorithmName != null ? AlgorithmName : DefaultAlgorithm; // Open an symmetric algorithm provider for the specified algorithm. var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName); // Decrypt data return CryptographicEngine.Decrypt(key, encBuffer, iv); }
/// <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 byte[] buildRemoveFriendBytes(CryptographicKey encryptionKey = null) { JObject updateObj = new JObject(); updateObj.Add("updateType", "request"); updateObj.Add("requestStatus", "removed"); return MessageBuilder.buildMessageBytes(updateObj, encryptionKey); }
public static AsymmetricCipherKeyPair GetRsaKeyPair(CryptographicKey key) { var privateKeyBuffer = key.Export(CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey); byte[] privateKeyBytes; CryptographicBuffer.CopyToByteArray(privateKeyBuffer, out privateKeyBytes); var asn1 = (Asn1Sequence) Asn1Object.FromByteArray(privateKeyBytes); var rsa = new RsaPrivateKeyStructure(asn1); var pubKey = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); var privKey = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); return new AsymmetricCipherKeyPair(pubKey, privKey); }
public static string DecryptString(IBuffer encBuffer, CryptographicKey key, IBuffer iv, String AlgorithmName = null) { //decrypt buffer var buffDecrypted = Decrypt(encBuffer, key, iv, AlgorithmName: AlgorithmName); // Convert the decrypted buffer to a string. return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecrypted); }
public static byte[] bulidSessionEstablishedBytes(CryptographicKey encryptionKey = null) { JObject updateObj = new JObject(); updateObj.Add("updateType", "session"); return MessageBuilder.buildMessageBytes(updateObj, encryptionKey); }
public void InitializeUniqueIdKeyPair(string keypair) { timestampKey = asym.ImportKeyPair(Convert.FromBase64String(keypair).AsBuffer()); UniqueId = Convert.ToBase64String(timestampKey.ExportPublicKey(CryptographicPublicKeyBlobType.Capi1PublicKey).ToArray()); }
// Encrypt data using the AES_ECB_PKCS7 Algorithim and the given key and return the encrypted data as a Hex encoded string public static string EncryptString(string data, CryptographicKey encryptionKey) { // Create the algorithim, the key, and a buffer to store the string that we want to encrypt IBuffer dataBuff = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8); // Encrypt the data into a buffer and then return a string represetnation of that buffer. There is no Initialization // vector needed when using ECB so it is set to null IBuffer encryptedBuff = CryptographicEngine.Encrypt(encryptionKey, dataBuff, null); return CryptographicBuffer.EncodeToHexString(encryptedBuff); }
/// <summary> /// Initializes a new instance of the <see cref="CryptographicKey" /> class. /// </summary> /// <param name="key">The WinRT cryptographic key.</param> /// <param name="symmetricAlgorithmProvider">The symmetric algorithm of the provider creating this key.</param> /// <param name="canExportPrivateKey"> /// A value indicating whether <see cref="Export(CryptographicPrivateKeyBlobType)"/> /// can be expected to work. /// </param> internal CryptographicKey(Platform.CryptographicKey key, SymmetricKeyAlgorithmProvider symmetricAlgorithmProvider, bool canExportPrivateKey) : this(key, canExportPrivateKey) { this.symmetricAlgorithmProvider = symmetricAlgorithmProvider; }
public SymmetricKeyEncryptor (SymmetricKeyAlgorithmProvider algorithm, CryptographicKey key, IBuffer iv) { this.algorithm = algorithm; this.key = key; this.iv = iv; }
/// <summary> /// Шифрование текста /// </summary> /// <param name="SourceText">Исходный (открытый) текст</param> /// <param name="InputKey">Ключ шифрование</param> /// <param name="AlgorythmName">Имя алгоритма шифрования</param> /// <returns>Зашифрованный текст</returns> public string EncryptMode(string SourceText, string InputKey, string AlgorythmName, string IV, string KeySize) { SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorythmName); IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE); IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE); //CryptoKey = Algorithm.CreateSymmetricKey(KeyBuffer); //######################### KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512); KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000); CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer); IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, Convert.ToUInt32(KeySize)/8); //string test = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial); CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial); //############### // CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer); //Надо присваивать IV пользовательское значение или генерированное значение IV if (AlgorythmName.Contains("CBC")) { IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE); } // Set the data to encrypt. SourceTextBuffer = CryptographicBuffer.ConvertStringToBinary(SourceText, BinaryStringEncoding.Utf16LE); // Encrypt EncryptBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Encrypt(CryptoKey, SourceTextBuffer, IVBuffer); //Convert to Base64 EncryptTextOutput = CryptographicBuffer.EncodeToBase64String(EncryptBuffer); string test = CryptographicBuffer.EncodeToBase64String(keyMaterial); //return test;// return EncryptTextOutput; }