/// <summary> /// Test the StreamMac class implementation /// <para>Throws an Exception on failure</</para> /// </summary> public static void StreamMacTest() { byte[] data; byte[] key; MemoryStream instrm; MemoryStream outstrm = new MemoryStream(); using (KeyGenerator kg = new KeyGenerator()) { data = kg.GetBytes(512); key = kg.GetBytes(64); } // data to digest instrm = new MemoryStream(data); byte[] code1; byte[] code2; using (StreamMac sm = new StreamMac(new SHA512HMAC(key))) { sm.Initialize(instrm); code1 = sm.ComputeMac(); } using (HMAC hm = new HMAC(new SHA512())) { hm.Initialize(new KeyParams(key)); code2 = hm.ComputeMac(data); } // compare the hash codes if (!Compare.AreEqual(code1, code2)) throw new Exception(); }
private byte[] MacTest2(string FileName, byte[] IKm) { using (FileStream inStream = new FileStream(FileName, FileMode.Open)) { using (StreamMac mac = new StreamMac(new SHA512HMAC(IKm))) { mac.Initialize(inStream); mac.IsConcurrent = false; return mac.ComputeMac(); } } }
/// <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(); })); } }
private bool MacTest3(byte[] IKm) { byte[] data = new CSPRng().GetBytes(33033); byte[] hash1; byte[] hash2; using (StreamMac mac1 = new StreamMac(new SHA512HMAC(IKm))) { mac1.Initialize(new MemoryStream(data)); mac1.IsConcurrent = false; hash1 = mac1.ComputeMac(); } using (SHA512HMAC mac2 = new SHA512HMAC(IKm)) hash2 = mac2.ComputeMac(data); return Compare.AreEqual(hash1, hash2); }
/// <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(); })); } }