public static ICrypto GetCrypto(CryptoAlgorithm algorithm) { ICrypto crypto = null; switch (algorithm) { case CryptoAlgorithm.DES: crypto = new Sym_DES( ); break; case CryptoAlgorithm.RC2: crypto = new Sym_RC2( ); break; case CryptoAlgorithm.Rijndael: crypto = new Sym_Rijndael( ); break; case CryptoAlgorithm.TripleDES: crypto = new Sym_TripleDES( ); break; case CryptoAlgorithm.RSA: crypto = new Asym_RSA( ); break; default: Debug.Assert(false); break; } Debug.Assert(crypto != null); return(crypto); }
public static ICrypto GetCrypto(CryptoAlgorithm algorithm) { switch (algorithm) { case CryptoAlgorithm.DES: return(new Sym_DES()); case CryptoAlgorithm.RC2: return(new Sym_RC2()); case CryptoAlgorithm.Rijndael: return(new Sym_Rijndael()); case CryptoAlgorithm.TripleDES: return(new Sym_TripleDES()); case CryptoAlgorithm.RSA: return(new Asym_RSA()); case CryptoAlgorithm.MD5: return(new Hash_MD5()); case CryptoAlgorithm.SHA1: return(new Hash_SHA1()); } return(null); }
public static ICrypto GetCrypto(CryptoAlgorithm algorithm) { switch (algorithm) { case CryptoAlgorithm.DES: return new Sym_DES(); case CryptoAlgorithm.RC2: return new Sym_RC2(); case CryptoAlgorithm.Rijndael: return new Sym_Rijndael(); case CryptoAlgorithm.TripleDES: return new Sym_TripleDES(); case CryptoAlgorithm.RSA: return new Asym_RSA(); case CryptoAlgorithm.MD5: return new Hash_MD5(); case CryptoAlgorithm.SHA1: return new Hash_SHA1(); } return null; }
/// <summary> /// Initializes a new instance of the SymmetricKey class. /// </summary> /// <param name="provider">One of the <see cref="CryptoProvider"/> values.</param> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <param name="buffer">An array of bytes that contains the key to import.</param> public SymmetricKey(CryptoProvider provider, CryptoAlgorithm algorithm, byte[] buffer) : this(provider) { if (buffer == null) { throw new ArgumentNullException(); } m_Handle = KeyFromBytes(m_Provider, algorithm, buffer); }
public static ICrypto GetCrypto( CryptoAlgorithm algorithm ) { ICrypto crypto = null; switch ( algorithm ) { case CryptoAlgorithm.DES: crypto = new Sym_DES( ); break; case CryptoAlgorithm.RC2: crypto = new Sym_RC2( ); break; case CryptoAlgorithm.Rijndael: crypto = new Sym_Rijndael( ); break; case CryptoAlgorithm.TripleDES: crypto = new Sym_TripleDES( ); break; case CryptoAlgorithm.RSA: crypto = new Asym_RSA( ); break; default: Debug.Assert( false ); break; } Debug.Assert( crypto != null ); return crypto; }
/// <summary> /// Initializes a new instance of the SymmetricKey class. /// </summary> /// <param name="provider">One of the <see cref="CryptoProvider"/> values.</param> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <exception cref="SecurityException">An error occurs when generating a new key.</exception> public SymmetricKey(CryptoProvider provider, CryptoAlgorithm algorithm) : this(provider) { m_Handle = 0; if (SspiProvider.CryptGenKey(m_Provider, new IntPtr((int)algorithm), SecurityConstants.CRYPT_EXPORTABLE, ref m_Handle) == 0) { throw new SecurityException("Cannot generate session key."); } }
public static void Execute(string choice) { var digest = new HmacDigest(); byte[] inputBuffer = new byte[1024]; Stream inputStream = Console.OpenStandardInput(inputBuffer.Length); Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length)); Console.SetBufferSize(128, 1024); if (choice == "1") { Console.WriteLine("Please enter text for Encrypt:"); string inputText = Console.ReadLine(); Console.WriteLine("\nEncryptKey:"); CryptoAlgorithm settingsDecryptor = new CryptoAlgorithm("ENCRYPT", "FSCS", new AesManaged()); var value = settingsDecryptor.Encrypt(inputText); Console.WriteLine(value); } else if (choice == "2") { Console.WriteLine("Public App Key: " + digest.PublicKey.ToString()); Console.WriteLine("\nDigest: " + digest.HashedStringBase64); Console.WriteLine("\nEpoch Time: " + digest.EpochTime.ToString()); } else if (choice == "3") { Console.WriteLine("Hit Enter to exit, Cya!!!"); Console.ReadLine(); } else { Console.WriteLine("Invalid Choice, Hit Enter to exit"); } }
private void Next_Pressed(object sender, RoutedEventArgs e) { if (cbAES.IsChecked == true) { crypto = new Crypto(CryptoAlgorithm.AES); cAlgo = CryptoAlgorithm.AES; KeysWindow kw = new KeysWindow(crypto, CryptoAlgorithm.AES); if (kw.ShowDialog() == true) { crypto = kw.crypto1; DialogResult = true; } } else if (cbRSA.IsChecked == true) { crypto = new Crypto(CryptoAlgorithm.RSA); cAlgo = CryptoAlgorithm.RSA; KeysWindow kw = new KeysWindow(crypto, CryptoAlgorithm.RSA); if (kw.ShowDialog() == true) { crypto = kw.crypto1; DialogResult = true; } } Close(); }
public static Stream DecryptDataToStream(byte[] Data, byte[] Key, byte[] IV, CryptoAlgorithm crypAlg = CryptoAlgorithm.Rijndael) { SymmetricCryptoHelper.CanPerformDecrypt(Data, Key, IV); byte[] decryptedData = null; if (crypAlg == CryptoAlgorithm.Rijndael) { using (Rijndael rijAlg = Rijndael.Create()) { rijAlg.Key = Key; rijAlg.IV = IV; ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); decryptedData = GetDecryptedDataFromCryptoStream(Data, decryptor); } return(new MemoryStream(decryptedData)); } else { using (Aes aesAlg = Aes.Create()) { aesAlg.Key = Key; aesAlg.IV = IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); decryptedData = GetDecryptedDataFromCryptoStream(Data, decryptor); } return(new MemoryStream(decryptedData)); } }
public void SimpleFactory_Test(CryptoAlgorithm algorithm, int keySize) { //Arrange => Act var cryptoEngine = CryptoEngineFactory.GetCryptoEngine(algorithm, keySize); //Assert Assert.IsNotNull(cryptoEngine, "Factory method didn't work"); }
/*internal SymmetricKey(int provider, int key, bool ownsProvider) : this(ownsProvider) { * if (key == 0 || provider == 0) * throw new ArgumentNullException(); * m_Provider = provider; * m_Handle = key; * m_PaddingMode = PaddingMode.None; * }*/ /*public SymmetricKey(CryptoProvider provider, CryptoAlgorithm algorithm) : this(provider) { * m_Handle = 0; * if (NativeMethods.CryptGenKey(m_Provider, new IntPtr((int)algorithm), NativeMethods.CRYPT_EXPORTABLE, ref m_Handle) == 0) * throw new CryptographicException("Cannot generate session key."); * }*/ public SymmetricKey(CryptoAlgorithm algorithm, byte[] buffer) : this() { if (buffer == null) { throw new ArgumentNullException("buffer", ResourceController.GetString("Error_ParamNull")); } m_Handle = KeyFromBytes(m_Provider, algorithm, buffer); }
/// <summary> /// /// </summary> /// <param name="algorithm"></param> /// <param name="sourse"></param> /// <returns></returns> public static string DecryptString(CryptoAlgorithm algorithm, string sourse) { if (sourse == null) { return(string.Empty); } return(Cryptographer.Decrypt(algorithm, sourse)); }
/// <summary> /// /// </summary> /// <param name="algorithm"></param> /// <param name="sourse"></param> /// <returns></returns> public static string EncrypString(CryptoAlgorithm algorithm, string sourse) { if (sourse == null) { return string.Empty; } return Cryptographer.Encrypt(algorithm, sourse); }
public static AsymmetricCrypto CreateAsymmetric(CryptoAlgorithm algorithm) { if (algorithm != CryptoAlgorithm.RSA && algorithm != CryptoAlgorithm.DSA) { throw new NotSupportedException(SR.GetString(SRKind.AlgorithmNotSupported, algorithm)); } return(Create(algorithm.ToString()) as AsymmetricCrypto); }
public Encryptor(CryptoAlgorithm algorithm, byte[] key) { SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithm.ToString()); provider.Key = key; provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; encryptor = provider.CreateEncryptor(); decryptor = provider.CreateDecryptor(); }
public void With_EncryptDecrypt() { CryptoAlgorithm algorithm = context.Build(); functionToInvoke = (data) => { var encrypted = algorithm.Encrypt(data); return(algorithm.Decrypt(encrypted)); }; }
/// <summary> /// Initializes a new instance of the RijndaelUnmanagedTransform class. /// </summary> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <param name="method">One of the <see cref="CryptoMethod"/> values.</param> /// <param name="key">The key to use.</param> /// <param name="iv">The IV to use.</param> /// <param name="mode">One of the <see cref="CipherMode"/> values.</param> /// <param name="feedback">The feedback size of the cryptographic operation in bits.</param> /// <param name="padding">One of the <see cref="PaddingMode"/> values.</param> public RijndaelUnmanagedTransform(CryptoAlgorithm algorithm, CryptoMethod method, byte[] key, byte[] iv, CipherMode mode, int feedback, PaddingMode padding) { m_Key = new SymmetricKey(CryptoProvider.RsaAes, algorithm, key); m_Key.IV = iv; m_Key.Mode = mode; if (mode == CipherMode.CFB) m_Key.FeedbackSize = feedback; m_Key.Padding = padding; m_BlockSize = 128; m_Method = method; }
private async Task <bool> ReceivePacketAsync_AES_256_CBC_SP() { CryptoAlgorithm alg = CryptoAlgorithm.AES_256_CBC_SP; int index = 1; byte[] ciphertext = new byte[16]; if (!await channel.ReceiveAsync(ciphertext, 0, 16)) { return(false); } if (!TryDecrypt(ciphertext, AesKey, ReceiveIV, out byte[] plaintext))
public Crypto(CryptoAlgorithm ca) { CryptoAlgorithmMode = ca; if (CryptoAlgorithmMode == CryptoAlgorithm.AES) { aes = new AesCryptoServiceProvider(); } else if (CryptoAlgorithmMode == CryptoAlgorithm.RSA) { rsa = new RSACryptoServiceProvider(); } }
public void Initialize(CryptoAlgorithm mMode) { mode = mMode; if (mode == CryptoAlgorithm.AES) { aes = new AesCryptoServiceProvider(); } else { rsa = new RSACryptoServiceProvider(); } }
public void Initialize(CryptoAlgorithm type) { mType = type; if (type == CryptoAlgorithm.AES) { aes = new AesCryptoServiceProvider(); } else if (type == CryptoAlgorithm.RSA) { rsa = new RSACryptoServiceProvider(); } }
public static HashCrypto CreateHash(CryptoAlgorithm algorithm) { if (algorithm != CryptoAlgorithm.MD5 && algorithm != CryptoAlgorithm.SHA1 && algorithm != CryptoAlgorithm.SHA256 && algorithm != CryptoAlgorithm.SHA384 && algorithm != CryptoAlgorithm.SHA512) { throw new NotSupportedException(SR.GetString(SRKind.AlgorithmNotSupported, algorithm)); } return(Create(algorithm.ToString()) as HashCrypto); }
/// <summary> /// Initializes a new instance of the RijndaelUnmanagedTransform class. /// </summary> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <param name="method">One of the <see cref="CryptoMethod"/> values.</param> /// <param name="key">The key to use.</param> /// <param name="iv">The IV to use.</param> /// <param name="mode">One of the <see cref="CipherMode"/> values.</param> /// <param name="feedback">The feedback size of the cryptographic operation in bits.</param> /// <param name="padding">One of the <see cref="PaddingMode"/> values.</param> public RijndaelUnmanagedTransform(CryptoAlgorithm algorithm, CryptoMethod method, byte[] key, byte[] iv, CipherMode mode, int feedback, PaddingMode padding) { m_Key = new SymmetricKey(CryptoProvider.RsaAes, algorithm, key); m_Key.IV = iv; m_Key.Mode = mode; if (mode == CipherMode.CFB) { m_Key.FeedbackSize = feedback; } m_Key.Padding = padding; m_BlockSize = 128; m_Method = method; }
public KeysWindow(Crypto crypto, CryptoAlgorithm ca) { InitializeComponent(); mode = ca; crypto1 = crypto; if (mode == CryptoAlgorithm.AES) { ButtonSetup(AESButtons); } else if (mode == CryptoAlgorithm.RSA) { ButtonSetup(RSAButtons); } }
public static SymmetricCrypto CreateSymmetric(CryptoAlgorithm algorithm) { if (algorithm != CryptoAlgorithm.DES && algorithm != CryptoAlgorithm.AES && algorithm != CryptoAlgorithm.RC2 && algorithm != CryptoAlgorithm.RC4 && algorithm != CryptoAlgorithm.Rijndael && algorithm != CryptoAlgorithm.TripleDES) { throw new NotSupportedException(SR.GetString(SRKind.AlgorithmNotSupported, algorithm)); } return(Create(algorithm.ToString()) as SymmetricCrypto); }
protected virtual void Dispose(bool disposing) { if (Disposed) { return; } if (disposing) { CryptoAlgorithm.Dispose(); } Disposed = true; }
private async Task <bool> ReceivePacketAsync_RSA_2048_OAEP() { CryptoAlgorithm alg = CryptoAlgorithm.RSA_2048_OAEP; int index = 1; byte[] ciphertext = new byte[256]; if (!await channel.ReceiveAsync(ciphertext, 0, 256)) { return(false); } byte[] plaintext; try { plaintext = RsaStatic.DecryptBlock(ciphertext, rsaKey); } catch (CryptographicException ex) { exceptionHandler.CloseConnection(ex); return(false); } byte id = plaintext[0]; // index = 1 if (!AssertInternal(id, alg) || !handler.ValidatePacket(id, alg, out PacketRule rule)) { return(false); } uint length; if (rule.Packet.ConstantLength.HasValue) { length = rule.Packet.ConstantLength.Value; } else { length = BitConverter.ToUInt32(plaintext, index); index += 4; if (!AssertSize(209, (int)length)) { return(false); // 214 - 1 (id) - 4 (uint) => 209 } } if (!AssertAvailable(plaintext.Length - index, (int)length)) { return(false); } parent.Log($"Received internal RSA packet: ID={id} Length={length}"); return(await handler.HandleInternalPacketAsync(rule, plaintext.TakeAt(index, (int)length))); }
public EncryptionToolWindow() { InitializeComponent(); SelectionWindow sw = new SelectionWindow(); if (sw.ShowDialog() == true) { myCrypto = sw.crypto; mode = sw.cAlgo; } else { Close(); } }
public static ICryptoEngine GetCryptoEngine(CryptoAlgorithm cryptoAlgorithm, params object[] constructorArguments) { ICryptoEngine cryptoEngine = null; switch (cryptoAlgorithm) { case CryptoAlgorithm.RijndaelManaged: cryptoEngine = (ICryptoEngine)Activator.CreateInstance(typeof(RijndaelCryptoEngine), constructorArguments); break; case CryptoAlgorithm.Aes: cryptoEngine = (ICryptoEngine)Activator.CreateInstance(typeof(AesCryptoEngine), constructorArguments); break; } return(cryptoEngine); }
private async Task <bool> ReceivePacketAsync_Plaintext() { CryptoAlgorithm alg = CryptoAlgorithm.None; byte id; // read packet id byte[] buffer = new byte[1]; if (!await channel.ReceiveAsync(buffer, 0, 1)) { return(false); } id = buffer[0]; if (!AssertInternal(id, alg) || !handler.ValidatePacket(id, alg, out PacketRule rule)) { return(false); } uint length; // read packet length if (rule.Packet.ConstantLength.HasValue) { length = rule.Packet.ConstantLength.Value; } else { buffer = new byte[4]; if (!await channel.ReceiveAsync(buffer, 0, 4)) { return(false); } length = BitConverter.ToUInt32(buffer, 0); if (!AssertSize(settings.MaxPacketSize, (int)length)) { return(false); } } buffer = new byte[length]; if (!await channel.ReceiveAsync(buffer, 0, (int)length)) // read packet content { return(false); } #if DEBUG parent.Log($"Received internal plaintext packet: ID={id} Length={length}"); #endif return(await handler.HandleInternalPacketAsync(rule, buffer)); }
private void EncryptButton_Click(object sender, RoutedEventArgs e) { byte[] textToEncodeBytes; if (filePath == string.Empty) { textToEncodeBytes = Encoding.ASCII.GetBytes(TextToEncryptTextBox.Text); } else { textToEncodeBytes = File.ReadAllBytes(filePath); } if (EncryptionKeyTextBox.Text.Length != 8) { MessageBox.Show("Key must be an 8byte string", "Error!"); return; } BitArray encryptionKey = new BitArray(Encoding.ASCII.GetBytes(EncryptionKeyTextBox.Text)); if (textToEncodeBytes.Length == 0) { MessageBox.Show("There is nothing to encode", "Error!"); } BitArray bitArrayToEncode = new BitArray(textToEncodeBytes).RevertEveryByte(); bool[] bitsToEncode = new bool[bitArrayToEncode.Count]; bitArrayToEncode.CopyTo(bitsToEncode, 0); DESBuilder builder = new DESBuilder(); builder.AddWholeDES(encryptionKey); CryptoAlgorithm des = builder.Build(); bool[] encrypted = des.Encrypt(bitsToEncode); encryptedBytes = encrypted.ToByteArray(); EncryptedTextBox.Text = Encoding.ASCII.GetString(encryptedBytes); filePath = string.Empty; //DecryptedTextBox.Text = Encoding.ASCII.GetString(des.Decrypt(encrypted).ToByteArray()); //byte[] returnMessage = messageWithoutPadding.ToByteArray(); //File.WriteAllBytes(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "decrypted.bmp"), returnMessage }
// constructor> // <functions #region receive internal async Task <bool> ReceivePacketAsync() { byte[] buffer = new byte[1]; if (!await channel.ReceiveAsync(buffer, 0, 1)) { return(false); } CryptoAlgorithm algorithm = (CryptoAlgorithm)buffer[0]; switch (algorithm) { case CryptoAlgorithm.None: return(await ReceivePacketAsync_Plaintext()); case CryptoAlgorithm.RSA_2048_OAEP: return(await ReceivePacketAsync_RSA_2048_OAEP()); case CryptoAlgorithm.AES_256_CBC_SP: if (!AssertKeyExchanged(CryptoAlgorithm.AES_256_CBC_SP) || !AssertAlgorithm(algorithm)) { return(false); } return(await ReceivePacketAsync_AES_256_CBC_SP()); case CryptoAlgorithm.AES_256_CBC_HMAC_SHA256_MP3: if (!AssertKeyExchanged(CryptoAlgorithm.AES_256_CBC_HMAC_SHA256_MP3) || !AssertAlgorithm(algorithm)) { return(false); } return(await ReceivePacketAsync_AES_256_CBC_HMAC_SHA_256_MP3()); case CryptoAlgorithm.AES_256_CBC_HMAC_SHA256_CTR: if (!AssertKeyExchanged(CryptoAlgorithm.AES_256_CBC_HMAC_SHA256_CTR) || !AssertAlgorithm(algorithm)) { return(false); } return(await ReceivePacketAsync_AES_256_CBC_HMAC_SHA_256_CTR()); default: exceptionHandler.CloseConnection("InvalidAlgorithm", $"Received packet with unknown algorithm ({algorithm}).", nameof(NetworkManager)); return(false); } }
/// <summary> /// /// </summary> /// <param name="algorithm"></param> /// <returns></returns> public static ICryptographer GetCryptographer(CryptoAlgorithm algorithm) { ICryptographer crypto = null; switch (algorithm) { case CryptoAlgorithm.DES: crypto = new DESCryptographer(); break; case CryptoAlgorithm.RC2: crypto = new RC2Cryptographer(); break; case CryptoAlgorithm.Rijndael: crypto = new RijndaelCryptographer(); break; case CryptoAlgorithm.TripleDES: crypto = new TripleDESCryptographer(); break; case CryptoAlgorithm.RSA: crypto = new RSACryptorapher(); break; case CryptoAlgorithm.MD5: crypto = new MD5HashCryptographer(); break; case CryptoAlgorithm.HMACMD5: crypto = new HMACMD5HashCryptographer(); break; case CryptoAlgorithm.SHA1: crypto = new SHA1HashCryptographer(); break; default: Debug.Assert(false); break; } Debug.Assert(crypto != null); return(crypto); }
public HmacDigest() { var Keys = new AppKeys(); CryptoAlgorithm secretDecryptor = new CryptoAlgorithm("ENCRYPT", "FSCS", new AesManaged()); PublicKey = Keys.Key; SecretKey = secretDecryptor.Decrypt(Keys.Secret); EpochTime = Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(SecretKey); HMACSHA256 sha = new HMACSHA256(keyByte); byte[] byteData = encoding.GetBytes(EpochTime.ToString()); byte[] hashedDataOutput = sha.ComputeHash(byteData); HashedString = ByteToString(hashedDataOutput); HashedStringBase64 = Convert.ToBase64String(hashedDataOutput); }
/// <summary> /// /// </summary> /// <param name="algorithm"></param> /// <returns></returns> public static ICryptographer GetCryptographer(CryptoAlgorithm algorithm) { ICryptographer crypto = null; switch (algorithm) { case CryptoAlgorithm.DES: crypto = new DESCryptographer(); break; case CryptoAlgorithm.RC2: crypto = new RC2Cryptographer(); break; case CryptoAlgorithm.Rijndael: crypto = new RijndaelCryptographer(); break; case CryptoAlgorithm.TripleDES: crypto = new TripleDESCryptographer(); break; case CryptoAlgorithm.RSA: crypto = new RSACryptorapher(); break; case CryptoAlgorithm.MD5: crypto = new MD5HashCryptographer(); break; case CryptoAlgorithm.HMACMD5: crypto = new HMACMD5HashCryptographer(); break; case CryptoAlgorithm.SHA1: crypto = new SHA1HashCryptographer(); break; default: Debug.Assert(false); break; } Debug.Assert(crypto != null); return crypto; }
private unsafe IntPtr KeyFromBytes(IntPtr provider, CryptoAlgorithm algorithm, byte[] key) { int dwFlags = NativeMethods.CRYPT_FIRST, dwSize, dwProvSessionKeySize = 0, dwPublicKeySize = 0, dwSessionBlob, offset = 0, algo = (int)algorithm; IntPtr provEnum = IntPtr.Zero, dwPrivKeyAlg = IntPtr.Zero, pbSessionBlob = IntPtr.Zero, hTempKey = IntPtr.Zero, hSessionKey = IntPtr.Zero; try { // Double check to see if this provider supports this algorithm // and key size bool found = false; provEnum = Marshal.AllocHGlobal(84 + IntPtr.Size); do { dwSize = 84 + IntPtr.Size; if (NativeMethods.CryptGetProvParam(provider, NativeMethods.PP_ENUMALGS_EX, provEnum, ref dwSize, dwFlags) == 0) break; dwFlags = 0; if (Marshal.ReadInt32(provEnum) == algo) found = true; } while (!found); if (!found) throw new CryptographicException(ResourceController.GetString("Error_AlgNotSupp")); // We have to get the key size(including padding) // from an HCRYPTKEY handle. PP_ENUMALGS_EX contains // the key size without the padding so we can't use it. if (NativeMethods.CryptGenKey(provider, algo, 0, ref hTempKey) == 0) throw new CryptographicException(ResourceController.GetString("Error_KeygenFailed")); dwSize = 4; // sizeof(int) if (NativeMethods.CryptGetKeyParam(hTempKey, NativeMethods.KP_KEYLEN, ref dwProvSessionKeySize, ref dwSize, 0) == 0) throw new CryptographicException(ResourceController.GetString("Error_GetKeyParams")); // Our key is too big, leave if ((key.Length * 8) > dwProvSessionKeySize) throw new CryptographicException(ResourceController.GetString("Error_BigKey")); // Get private key's algorithm dwSize = 4; //sizeof(ALG_ID) if (NativeMethods.CryptGetKeyParam(m_ExponentOfOne, NativeMethods.KP_ALGID, ref dwPrivKeyAlg, ref dwSize, 0) == 0) throw new CryptographicException(ResourceController.GetString("Error_PrivateKeyAlg")); // Get private key's length in bits dwSize = 4; // sizeof(DWORD) if (NativeMethods.CryptGetKeyParam(m_ExponentOfOne, NativeMethods.KP_KEYLEN, ref dwPublicKeySize, ref dwSize, 0) == 0) throw new CryptographicException(ResourceController.GetString("Error_KeyLength")); // calculate Simple blob's length dwSessionBlob = (dwPublicKeySize / 8) + 4 /*sizeof(ALG_ID)*/ + 4 + IntPtr.Size /*sizeof(BLOBHEADER)*/; // allocate simple blob buffer pbSessionBlob = Marshal.AllocHGlobal(dwSessionBlob); // SIMPLEBLOB Format is documented in SDK // Copy header to buffer PUBLICKEYSTRUC pks = new PUBLICKEYSTRUC(); pks.bType = NativeMethods.SIMPLEBLOB; pks.bVersion = 2; pks.reserved = 0; pks.aiKeyAlg = algo; Marshal.StructureToPtr(pks, pbSessionBlob, false); Marshal.WriteIntPtr(pbSessionBlob, offset = Marshal.SizeOf(pks), dwPrivKeyAlg); offset += 4; // sizeof(ALG_ID) // Place the key material in reverse order for (int i = 0; i < key.Length; i++) { Marshal.WriteByte(pbSessionBlob, offset + key.Length - i - 1, key[i]); } // 3 is for the first reserved byte after the key material + the 2 reserved bytes at the end. dwSize = dwSessionBlob - (4 /*sizeof(ALG_ID)*/ + IntPtr.Size + 4 /*sizeof(BLOBHEADER)*/ + key.Length + 3); offset += key.Length + 1; // Generate random data for the rest of the buffer // (except that last two bytes) byte* buffer = (byte*)pbSessionBlob.ToPointer() + offset; if (NativeMethods.CryptGenRandom(provider, dwSize, buffer) == 0) throw new CryptographicException(ResourceController.GetString("Error_Randomizer")); for (int i = 0; i < dwSize; i++) { if (Marshal.ReadByte(pbSessionBlob, offset) == 0) Marshal.WriteByte(pbSessionBlob, offset, 1); offset++; } Marshal.WriteByte(pbSessionBlob, dwSessionBlob - 2, 2); if (NativeMethods.CryptImportKey(provider, pbSessionBlob, dwSessionBlob, m_ExponentOfOne, NativeMethods.CRYPT_EXPORTABLE, ref hSessionKey) == 0) throw new CryptographicException(ResourceController.GetString("Error_KeyImport")); } finally { if (provEnum != IntPtr.Zero) Marshal.FreeHGlobal(provEnum); if (hTempKey != IntPtr.Zero) NativeMethods.CryptDestroyKey(hTempKey); if (pbSessionBlob != IntPtr.Zero) Marshal.FreeHGlobal(pbSessionBlob); } return hSessionKey; }
/*internal SymmetricKey(int provider, int key, bool ownsProvider) : this(ownsProvider) { if (key == 0 || provider == 0) throw new ArgumentNullException(); m_Provider = provider; m_Handle = key; m_PaddingMode = PaddingMode.None; }*/ /*public SymmetricKey(CryptoProvider provider, CryptoAlgorithm algorithm) : this(provider) { m_Handle = 0; if (NativeMethods.CryptGenKey(m_Provider, new IntPtr((int)algorithm), NativeMethods.CRYPT_EXPORTABLE, ref m_Handle) == 0) throw new CryptographicException("Cannot generate session key."); }*/ public SymmetricKey(CryptoAlgorithm algorithm, byte[] buffer) : this() { if (buffer == null) throw new ArgumentNullException("buffer", ResourceController.GetString("Error_ParamNull")); m_Handle = KeyFromBytes(m_Provider, algorithm, buffer); }
/// <summary> /// Negotiates the initialization vector. /// </summary> /// <param name="initializationVector">The initializatino vector.</param> /// <param name="algorithm">The algorithm.</param> public virtual void NegotiateInitializationVector(byte[] initializationVector, CryptoAlgorithm algorithm) { Logger.Instance.Info(string.Format("Initialization vector for crypto algorithm <{0}> sent", algorithm)); this.subscribers.ForEach(callback => callback.NotifyNegotiateInitializationVector(initializationVector, algorithm)); }
/// <summary> /// Negotiates the key. /// </summary> /// <param name="key">The key.</param> /// <param name="algorithm">The algorithm.</param> public virtual void NegotiateKey(byte[] key, CryptoAlgorithm algorithm) { Logger.Instance.Info(string.Format("Key for crypto algorithm <{0}> sent", algorithm)); this.subscribers.ForEach(callback => callback.NotifyNegotiateKey(key, algorithm)); }
/// <summary> /// Notifies the negotiate key. /// </summary> /// <param name="key">The key.</param> /// <param name="algorithm">The algorithm.</param> public void NotifyNegotiateKey(byte[] key, CryptoAlgorithm algorithm) { var cp = this.GetCryptoProvider(algorithm); cp.Key = key; }
/// <summary> /// /// </summary> /// <param name="algorithm"></param> /// <param name="plainConnectString"></param> /// <returns></returns> public static string Encrypt(CryptoAlgorithm algorithm, string plainConnectString) { ICryptographer cryptographer = GetCryptographer(algorithm); return cryptographer.Encrypt(plainConnectString); }
/// <summary> /// Notifies the negotiate initialization vector. /// </summary> /// <param name="initializationVector">The initialization vector.</param> /// <param name="algorithm">The algorithm.</param> public void NotifyNegotiateInitializationVector(byte[] initializationVector, CryptoAlgorithm algorithm) { var cp = this.GetCryptoProvider(algorithm); cp.InitalizationVector = initializationVector; }
/// <summary> /// Initializes a new instance of the SymmetricKey class. /// </summary> /// <param name="provider">One of the <see cref="CryptoProvider"/> values.</param> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <param name="buffer">An array of bytes that contains the key to import.</param> public SymmetricKey(CryptoProvider provider, CryptoAlgorithm algorithm, byte[] buffer) : this(provider) { if (buffer == null) throw new ArgumentNullException(); m_Handle = KeyFromBytes(m_Provider, algorithm, buffer); }
/// <summary> /// Gets the crypto provider. /// </summary> /// <param name="algorithm">The algorithm.</param> /// <returns>The crypto provider.</returns> private ICryptoProvider GetCryptoProvider(CryptoAlgorithm algorithm) { return (from c in this.CryptoProviders where c.Metadata.Algorithm == algorithm select c.Value).FirstOrDefault(); }
/// <summary> /// Imports a specified key. /// </summary> /// <param name="provider">The handle of the CSP.</param> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <param name="key">The key to import.</param> /// <returns>The handle of the symmetric key.</returns> /// <exception cref="SecurityException">An error occurs while importing the specified key.</exception> private int KeyFromBytes(int provider, CryptoAlgorithm algorithm, byte[] key) { int dwFlags = SecurityConstants.CRYPT_FIRST, dwSize, dwProvSessionKeySize = 0, dwPublicKeySize = 0, dwSessionBlob, offset = 0, hTempKey = 0, hSessionKey = 0; IntPtr algo = new IntPtr((int)algorithm), dwPrivKeyAlg = IntPtr.Zero, pbSessionBlob = IntPtr.Zero; IntPtr provEnum = IntPtr.Zero; try { // Double check to see if this provider supports this algorithm // and key size bool found = false; provEnum = Marshal.AllocHGlobal(84 + IntPtr.Size); do { dwSize = 84 + IntPtr.Size; if (SspiProvider.CryptGetProvParam(provider, SecurityConstants.PP_ENUMALGS_EX, provEnum, ref dwSize, dwFlags) == 0) break; dwFlags = 0; if (Marshal.ReadIntPtr(provEnum) == algo) found = true; } while (!found); if (!found) throw new SecurityException("CSP does not support selected algorithm."); // We have to get the key size(including padding) // from an HCRYPTKEY handle. PP_ENUMALGS_EX contains // the key size without the padding so we can't use it. if (SspiProvider.CryptGenKey(provider, algo, 0, ref hTempKey) == 0) throw new SecurityException("Cannot generate temporary key."); dwSize = 4; // sizeof(int) if (SspiProvider.CryptGetKeyParam(hTempKey, SecurityConstants.KP_KEYLEN, ref dwProvSessionKeySize, ref dwSize, 0) == 0) throw new SecurityException("Cannot retrieve key parameters."); // Our key is too big, leave if ((key.Length * 8) > dwProvSessionKeySize) throw new SecurityException("Key too big."); // Get private key's algorithm dwSize = IntPtr.Size; //sizeof(ALG_ID) if (SspiProvider.CryptGetKeyParam(m_ExponentOfOne, SecurityConstants.KP_ALGID, ref dwPrivKeyAlg, ref dwSize, 0) == 0) throw new SecurityException("Unable to get the private key's algorithm."); // Get private key's length in bits dwSize = 4; // sizeof(DWORD) if (SspiProvider.CryptGetKeyParam(m_ExponentOfOne, SecurityConstants.KP_KEYLEN, ref dwPublicKeySize, ref dwSize, 0) == 0) throw new SecurityException("Unable to get the key length."); // calculate Simple blob's length dwSessionBlob = (dwPublicKeySize / 8) + IntPtr.Size /*sizeof(ALG_ID)*/ + 4 + IntPtr.Size /*sizeof(BLOBHEADER)*/; // allocate simple blob buffer pbSessionBlob = Marshal.AllocHGlobal(dwSessionBlob); // SIMPLEBLOB Format is documented in SDK // Copy header to buffer PUBLICKEYSTRUC pks = new PUBLICKEYSTRUC(); pks.bType = SecurityConstants.SIMPLEBLOB; pks.bVersion = 2; pks.reserved = 0; pks.aiKeyAlg = algo; Marshal.StructureToPtr(pks, pbSessionBlob, false); Marshal.WriteIntPtr(pbSessionBlob, offset = Marshal.SizeOf(pks), dwPrivKeyAlg); offset += IntPtr.Size; // sizeof(ALG_ID) // Place the key material in reverse order for (int i = 0; i < key.Length; i++) { Marshal.WriteByte(pbSessionBlob, offset + key.Length - i - 1, key[i]); } // 3 is for the first reserved byte after the key material + the 2 reserved bytes at the end. dwSize = dwSessionBlob - (IntPtr.Size /*sizeof(ALG_ID)*/ + IntPtr.Size + 4 /*sizeof(BLOBHEADER)*/ + key.Length + 3); offset += key.Length + 1; // Generate random data for the rest of the buffer // (except that last two bytes) if (SspiProvider.CryptGenRandom(provider, dwSize, new IntPtr(pbSessionBlob.ToInt64() + offset)) == 0) throw new SecurityException("Could not generate random data."); for (int i = 0; i < dwSize; i++) { if (Marshal.ReadByte(pbSessionBlob, offset) == 0) Marshal.WriteByte(pbSessionBlob, offset, 1); offset++; } Marshal.WriteByte(pbSessionBlob, dwSessionBlob - 2, 2); if (SspiProvider.CryptImportKey( provider, pbSessionBlob, dwSessionBlob, m_ExponentOfOne, SecurityConstants.CRYPT_EXPORTABLE, ref hSessionKey) == 0) throw new SecurityException("Cannot import key [key has right size?]."); } finally { if (provEnum != IntPtr.Zero) Marshal.FreeHGlobal(provEnum); if (hTempKey != 0) SspiProvider.CryptDestroyKey(hTempKey); if (pbSessionBlob != IntPtr.Zero) Marshal.FreeHGlobal(pbSessionBlob); } return hSessionKey; }
/// <summary> /// Initializes a new instance of the SymmetricKey class. /// </summary> /// <param name="provider">One of the <see cref="CryptoProvider"/> values.</param> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <exception cref="SecurityException">An error occurs when generating a new key.</exception> public SymmetricKey(CryptoProvider provider, CryptoAlgorithm algorithm) : this(provider) { m_Handle = 0; if (SspiProvider.CryptGenKey(m_Provider, new IntPtr((int)algorithm), SecurityConstants.CRYPT_EXPORTABLE, ref m_Handle) == 0) throw new SecurityException("Cannot generate session key."); }
/// <summary> /// /// </summary> /// <param name="algorithm"></param> /// <param name="encryptedBase64ConnectString"></param> /// <returns></returns> public static string Decrypt(CryptoAlgorithm algorithm, string encryptedBase64ConnectString) { ICryptographer cryptographer = GetCryptographer(algorithm); return cryptographer.Decrypt(encryptedBase64ConnectString); }