/// <remarks> /// This method demonstrates using a PackageFactory to extract a key. /// StreamMac to verify with a keyed HMAC, that tests the encrypted file before it is conditionally decrypted. /// If accepted the stream is then decrypted using the StreamCipher class. /// </remarks> private void Decrypt() { CipherDescription cipherDesc; KeyParams keyParam; byte[] extKey; try { using (FileStream inStream = new FileStream(_inputPath, FileMode.Open, FileAccess.Read)) { byte[] keyId = MessageHeader.GetKeyId(inStream); // get the keyheader and key material from the key file using (PackageFactory keyFactory = new PackageFactory(_keyFilePath, _container.Authority)) { if (keyFactory.AccessScope == KeyScope.NoAccess) { MessageBox.Show(keyFactory.LastError); return; } keyFactory.Extract(keyId, out cipherDesc, out keyParam, out extKey); } // offset start position is base header + Mac size int hdrOffset = MessageHeader.GetHeaderSize + cipherDesc.MacSize; // decrypt file extension and create a unique path _outputPath = Utilities.GetUniquePath(_outputPath + MessageHeader.GetExtension(inStream, extKey)); // if a signing key, test the mac: (MacSize = 0; not signed) if (cipherDesc.MacSize > 0) { // get the hmac for the encrypted file; this could be made selectable // via the KeyHeaderStruct MacDigest and MacSize members. using (StreamMac mstrm = new StreamMac(new SHA512HMAC(keyParam.IKM))) { // get the message header mac byte[] chksum = MessageHeader.GetMessageMac(inStream, cipherDesc.MacSize); // initialize mac stream inStream.Seek(hdrOffset, SeekOrigin.Begin); mstrm.Initialize(inStream); // get the mac; offset by header length + Mac and specify adjusted length byte[] hash = mstrm.ComputeMac(inStream.Length - hdrOffset, hdrOffset); // compare, notify and abort on failure if (!Compare.AreEqual(chksum, hash)) { MessageBox.Show("Message hash does not match! The file has been tampered with."); return; } } } // with this constructor, the StreamCipher class creates the cryptographic // engine using the description contained in the CipherDescription structure. // The (cipher and) engine are automatically destroyed in the cipherstream dispose using (StreamCipher cstrm = new StreamCipher(false, cipherDesc, keyParam)) { using (FileStream outStream = new FileStream(_outputPath, FileMode.Create, FileAccess.Write)) { // start at an input offset equal to the message header size inStream.Seek(hdrOffset, SeekOrigin.Begin); // use a percentage counter cstrm.ProgressPercent += new StreamCipher.ProgressDelegate(OnProgressPercent); // initialize internals cstrm.Initialize(inStream, outStream); // write the decrypted output to file cstrm.Write(); } } } // destroy the key keyParam.Dispose(); } catch (Exception ex) { if (File.Exists(_outputPath)) File.Delete(_outputPath); string message = ex.Message == null ? "" : ex.Message; MessageBox.Show("An error occured, the file could not be encrypted! " + message); } finally { Invoke(new MethodInvoker(() => { Reset(); })); } }
/// <summary> /// Test the StreamCipher class implementation /// <para>Throws an Exception on failure</</para> /// </summary> public static void StreamCipherTest() { const int BLSZ = 1024; KeyParams key; byte[] data; MemoryStream instrm; MemoryStream outstrm = new MemoryStream(); using (KeyGenerator kg = new KeyGenerator()) { // get the key key = kg.GetKeyParams(32, 16); // 2048 bytes data = kg.GetBytes(BLSZ * 2); } // data to encrypt instrm = new MemoryStream(data); // Encrypt a stream // // create the outbound cipher using (ICipherMode cipher = new CTR(new RDX())) { // initialize the cipher for encryption cipher.Initialize(true, key); // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // encrypt the stream using (StreamCipher sc = new StreamCipher(cipher)) { sc.Initialize(instrm, outstrm); // encrypt the buffer sc.Write(); } } // reset stream position outstrm.Seek(0, SeekOrigin.Begin); MemoryStream tmpstrm = new MemoryStream(); // Decrypt a stream // // create the decryption cipher using (ICipherMode cipher = new CTR(new RDX())) { // initialize the cipher for decryption cipher.Initialize(false, key); // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // decrypt the stream using (StreamCipher sc = new StreamCipher(cipher)) { sc.Initialize(outstrm, tmpstrm); // process the encrypted bytes sc.Write(); } } // compare decrypted output with data if (!Compare.AreEqual(tmpstrm.ToArray(), data)) throw new Exception(); }
/// <remarks> /// This method demonstrates using a PackageFactory and StreamCipher class to /// both encrypt a file, and optionally sign the message with an SHA512 HMAC. /// See the StreamCipher and StreamMac documentation for more examples. /// </remarks> private void Encrypt() { CipherDescription keyHeader; KeyParams keyParam; try { byte[] keyId = null; byte[] extKey = null; // get the keyheader and key material from the key file using (PackageFactory keyFactory = new PackageFactory(_keyFilePath, _container.Authority)) { // get the key info PackageInfo pki = keyFactory.KeyInfo(); if (!keyFactory.AccessScope.Equals(KeyScope.Creator)) { MessageBox.Show(keyFactory.LastError); return; } keyId = (byte[])keyFactory.NextKey(out keyHeader, out keyParam, out extKey).Clone(); } // offset start position is base header + Mac size int hdrOffset = MessageHeader.GetHeaderSize + keyHeader.MacSize; // with this constructor, the StreamCipher class creates the cryptographic // engine using the description in the CipherDescription. // The (cipher and) engine are destroyed in the cipherstream dispose using (StreamCipher cstrm = new StreamCipher(true, keyHeader, keyParam)) { using (FileStream inStream = new FileStream(_inputPath, FileMode.Open, FileAccess.Read)) { using (FileStream outStream = new FileStream(_outputPath, FileMode.Create, FileAccess.ReadWrite)) { // start at an output offset equal to the message header + MAC length outStream.Seek(hdrOffset, SeekOrigin.Begin); // use a percentage counter cstrm.ProgressPercent += new StreamCipher.ProgressDelegate(OnProgressPercent); // initialize internals cstrm.Initialize(inStream, outStream); // write the encrypted output to file cstrm.Write(); // write the key id to the header MessageHeader.SetKeyId(outStream, keyId); // write the encrypted file extension MessageHeader.SetExtension(outStream, MessageHeader.GetEncryptedExtension(Path.GetExtension(_inputPath), extKey)); // if this is a signing key, calculate the mac if (keyHeader.MacSize > 0) { // Get the mac for the encrypted file; Mac engine is SHA512 by default, // configurable via the CipherDescription MacSize and MacEngine members. // This is where you would select and initialize the correct Digest via the // CipherDescription members, and initialize the corresponding digest. // For expedience, this example is fixed on the default SHA512. // An optional progress event is available in the StreamMac class. using (StreamMac mstrm = new StreamMac(new SHA512HMAC(keyParam.IKM))) { // seek to end of header outStream.Seek(hdrOffset, SeekOrigin.Begin); // initialize mac stream mstrm.Initialize(outStream); // get the hash; specify offset and adjusted size byte[] hash = mstrm.ComputeMac(outStream.Length - hdrOffset, hdrOffset); // write the keyed hash value to the message header MessageHeader.SetMessageMac(outStream, hash); } } } } } // destroy the key keyParam.Dispose(); } catch (Exception ex) { if (File.Exists(_outputPath)) File.Delete(_outputPath); string message = ex.Message == null ? "" : ex.Message; MessageBox.Show("An error occured, the file could not be encrypted! " + message); } finally { Invoke(new MethodInvoker(() => { Reset(); })); } }