PageRenderTime 27ms CodeModel.GetById 17ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/Mono.Security.Cryptography/CryptoService.cs

http://github.com/jbevain/cecil
C# | 204 lines | 142 code | 43 blank | 19 comment | 12 complexity | ce8a7ac234de78552d317d1c37ee1cb4 MD5 | raw file
  1//
  2// Author:
  3//   Jb Evain (jbevain@gmail.com)
  4//
  5// Copyright (c) 2008 - 2015 Jb Evain
  6// Copyright (c) 2008 - 2011 Novell, Inc.
  7//
  8// Licensed under the MIT/X11 license.
  9//
 10
 11using System;
 12using System.IO;
 13using System.Reflection;
 14using System.Security.Cryptography;
 15using System.Runtime.Serialization;
 16
 17using Mono.Security.Cryptography;
 18
 19using Mono.Cecil.PE;
 20
 21namespace Mono.Cecil {
 22
 23	// Most of this code has been adapted
 24	// from Jeroen Frijters' fantastic work
 25	// in IKVM.Reflection.Emit. Thanks!
 26
 27	static class CryptoService {
 28
 29		public static byte [] GetPublicKey (WriterParameters parameters)
 30		{
 31			using (var rsa = parameters.CreateRSA ()) {
 32				var cspBlob = CryptoConvert.ToCapiPublicKeyBlob (rsa);
 33				var publicKey = new byte [12 + cspBlob.Length];
 34				Buffer.BlockCopy (cspBlob, 0, publicKey, 12, cspBlob.Length);
 35				// The first 12 bytes are documented at:
 36				// http://msdn.microsoft.com/library/en-us/cprefadd/html/grfungethashfromfile.asp
 37				// ALG_ID - Signature
 38				publicKey [1] = 36;
 39				// ALG_ID - Hash
 40				publicKey [4] = 4;
 41				publicKey [5] = 128;
 42				// Length of Public Key (in bytes)
 43				publicKey [8] = (byte) (cspBlob.Length >> 0);
 44				publicKey [9] = (byte) (cspBlob.Length >> 8);
 45				publicKey [10] = (byte) (cspBlob.Length >> 16);
 46				publicKey [11] = (byte) (cspBlob.Length >> 24);
 47				return publicKey;
 48			}
 49		}
 50
 51		public static void StrongName (Stream stream, ImageWriter writer, WriterParameters parameters)
 52		{
 53			int strong_name_pointer;
 54
 55			var strong_name = CreateStrongName (parameters, HashStream (stream, writer, out strong_name_pointer));
 56			PatchStrongName (stream, strong_name_pointer, strong_name);
 57		}
 58
 59		static void PatchStrongName (Stream stream, int strong_name_pointer, byte [] strong_name)
 60		{
 61			stream.Seek (strong_name_pointer, SeekOrigin.Begin);
 62			stream.Write (strong_name, 0, strong_name.Length);
 63		}
 64
 65		static byte [] CreateStrongName (WriterParameters parameters, byte [] hash)
 66		{
 67			const string hash_algo = "SHA1";
 68
 69			using (var rsa = parameters.CreateRSA ()) {
 70				var formatter = new RSAPKCS1SignatureFormatter (rsa);
 71				formatter.SetHashAlgorithm (hash_algo);
 72
 73				byte [] signature = formatter.CreateSignature (hash);
 74				Array.Reverse (signature);
 75
 76				return signature;
 77			}
 78		}
 79
 80		static byte [] HashStream (Stream stream, ImageWriter writer, out int strong_name_pointer)
 81		{
 82			const int buffer_size = 8192;
 83
 84			var text = writer.text;
 85			var header_size = (int) writer.GetHeaderSize ();
 86			var text_section_pointer = (int) text.PointerToRawData;
 87			var strong_name_directory = writer.GetStrongNameSignatureDirectory ();
 88
 89			if (strong_name_directory.Size == 0)
 90				throw new InvalidOperationException ();
 91
 92			strong_name_pointer = (int) (text_section_pointer
 93				+ (strong_name_directory.VirtualAddress - text.VirtualAddress));
 94			var strong_name_length = (int) strong_name_directory.Size;
 95
 96			var sha1 = new SHA1Managed ();
 97			var buffer = new byte [buffer_size];
 98			using (var crypto_stream = new CryptoStream (Stream.Null, sha1, CryptoStreamMode.Write)) {
 99				stream.Seek (0, SeekOrigin.Begin);
100				CopyStreamChunk (stream, crypto_stream, buffer, header_size);
101
102				stream.Seek (text_section_pointer, SeekOrigin.Begin);
103				CopyStreamChunk (stream, crypto_stream, buffer, (int) strong_name_pointer - text_section_pointer);
104
105				stream.Seek (strong_name_length, SeekOrigin.Current);
106				CopyStreamChunk (stream, crypto_stream, buffer, (int) (stream.Length - (strong_name_pointer + strong_name_length)));
107			}
108
109			return sha1.Hash;
110		}
111
112		static void CopyStreamChunk (Stream stream, Stream dest_stream, byte [] buffer, int length)
113		{
114			while (length > 0) {
115				int read = stream.Read (buffer, 0, System.Math.Min (buffer.Length, length));
116				dest_stream.Write (buffer, 0, read);
117				length -= read;
118			}
119		}
120
121		public static byte [] ComputeHash (string file)
122		{
123			if (!File.Exists (file))
124				return Empty<byte>.Array;
125
126			using (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read))
127				return ComputeHash (stream);
128		}
129
130		public static byte [] ComputeHash (Stream stream)
131		{
132			const int buffer_size = 8192;
133
134			var sha1 = new SHA1Managed ();
135			var buffer = new byte [buffer_size];
136
137			using (var crypto_stream = new CryptoStream (Stream.Null, sha1, CryptoStreamMode.Write))
138				CopyStreamChunk (stream, crypto_stream, buffer, (int) stream.Length);
139
140			return sha1.Hash;
141		}
142
143		public static byte [] ComputeHash (params ByteBuffer [] buffers)
144		{
145			var sha1 = new SHA1Managed ();
146
147			using (var crypto_stream = new CryptoStream (Stream.Null, sha1, CryptoStreamMode.Write)) {
148				for (int i = 0; i < buffers.Length; i++) {
149					crypto_stream.Write (buffers [i].buffer, 0, buffers [i].length);
150				}
151			}
152
153			return sha1.Hash;
154		}
155
156		public static Guid ComputeGuid (byte [] hash)
157		{
158			// From corefx/src/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs
159			var guid = new byte [16];
160			Buffer.BlockCopy (hash, 0, guid, 0, 16);
161
162			// modify the guid data so it decodes to the form of a "random" guid ala rfc4122
163			guid [7] = (byte) ((guid [7] & 0x0f) | (4 << 4));
164			guid [8] = (byte) ((guid [8] & 0x3f) | (2 << 6));
165
166			return new Guid (guid);
167		}
168	}
169
170	static partial class Mixin {
171
172		public static RSA CreateRSA (this WriterParameters writer_parameters)
173		{
174			byte [] key;
175			string key_container;
176
177			if (writer_parameters.StrongNameKeyBlob != null)
178				return CryptoConvert.FromCapiKeyBlob (writer_parameters.StrongNameKeyBlob);
179
180			if (writer_parameters.StrongNameKeyContainer != null)
181				key_container = writer_parameters.StrongNameKeyContainer;
182			else if (!TryGetKeyContainer (writer_parameters.StrongNameKeyPair, out key, out key_container))
183				return CryptoConvert.FromCapiKeyBlob (key);
184
185			var parameters = new CspParameters {
186				Flags = CspProviderFlags.UseMachineKeyStore,
187				KeyContainerName = key_container,
188				KeyNumber = 2,
189			};
190
191			return new RSACryptoServiceProvider (parameters);
192		}
193
194		static bool TryGetKeyContainer (ISerializable key_pair, out byte [] key, out string key_container)
195		{
196			var info = new SerializationInfo (typeof (StrongNameKeyPair), new FormatterConverter ());
197			key_pair.GetObjectData (info, new StreamingContext ());
198
199			key = (byte []) info.GetValue ("_keyPairArray", typeof (byte []));
200			key_container = info.GetString ("_keyPairContainer");
201			return key_container != null;
202		}
203	}
204}