Beispiel #1
0
        public void TestSealOpen()
        {
            string inputMsg = "This is a message";
            byte[] input = Encoding.ASCII.GetBytes(inputMsg);
            const int numKeys = 10;
            var rsas = new RSA[numKeys];
            var pkeys = new CryptoKey[numKeys];
            for (int i = 0; i < numKeys; i++) {
                rsas[i] = new RSA();
                rsas[i].GenerateKeys(1024, BigNumber.One, null, null);
                pkeys[i] = new CryptoKey(rsas[i]);
            }

            try {
                foreach (var cipher in Ciphers(true)) {
                    using (var cc = new CipherContext(cipher)) {
                        var env = cc.Seal(pkeys, input);
                        Assert.AreNotEqual(input, env.Data);

                        for (int i = 0; i < numKeys; i++) {
                            var result = cc.Open(env.Data, env.Keys[i], env.IV, pkeys[i]);
                            Assert.AreEqual(input, result);
                        }
                    }
                }
            }
            finally {
                for (int i = 0; i < numKeys; i++) {
                    pkeys[i].Dispose();
                    rsas[i].Dispose();
                }
            }
        }
Beispiel #2
0
		public void TestRsaSha1()
		{
			using (Configuration cfg = new Configuration("openssl.cnf"))
			{
				// Test RSA/SHA1 with other SelfSigned method
				BigNumber bn = 0x10001;
				CryptoKey key;

				using (RSA rsa = new RSA())
				{
					rsa.GenerateKeys(2048, bn, OnGenerator, null);
					key = new CryptoKey(rsa);
					// rsa is assigned, we no longer need this instance
				}

				using (var root = X509CertificateAuthority.SelfSigned(
					                  cfg,
					                  new SimpleSerialNumber(),
					                  key,
					                  MessageDigest.SHA1,
					                  "Root1",
					                  DateTime.Now,
					                  TimeSpan.FromDays(365)))
				{
					Console.WriteLine(root.Certificate);
				}
			}
		}
Beispiel #3
0
		/// <summary>
		/// Calls X509_REQ_new() and then initializes version, subject, and key.
		/// </summary>
		/// <param name="version"></param>
		/// <param name="subject"></param>
		/// <param name="key"></param>
		public X509Request(int version, X509Name subject, CryptoKey key)
			: this()
		{
			this.Version = version;
			this.Subject = subject;
			this.PublicKey = key;
		}
Beispiel #4
0
        public void CanAddRequestExtensions()
        {
            var extList = new List<X509V3ExtensionValue> {
                new X509V3ExtensionValue("subjectAltName", false, "DNS:foo.com,DNS:bar.org"),
                new X509V3ExtensionValue("keyUsage", false, "cRLSign,keyCertSign"),
            };

            var start = DateTime.Now;
            var end = start + TimeSpan.FromMinutes(10);
            using (var key = new CryptoKey(RSA.FromPrivateKey(new BIO(RSA_KEY))))
            using (var request = new X509Request(1,new X509Name("foo"),key))
            {
                OpenSSL.Core.Stack<X509Extension> extensions = new OpenSSL.Core.Stack<X509Extension>();
                foreach (var extValue in extList)
                {
                    using (var ext = new X509Extension(request, extValue.Name, extValue.IsCritical, extValue.Value))
                    {
                        Console.WriteLine(ext);
                        extensions.Add(ext);
                    }
                }

                request.AddExtensions(extensions);

                Assert.AreEqual(EXPECTED_CERT, request.PEM);
            }
        }
        public void CanAddExtensions()
        {
            X509V3ExtensionList extList = new X509V3ExtensionList();
            extList.Add(new X509V3ExtensionValue("subjectKeyIdentifier", false, "hash"));
            extList.Add(new X509V3ExtensionValue("authorityKeyIdentifier", false, "keyid:always,issuer:always"));
            extList.Add(new X509V3ExtensionValue("basicConstraints", true, "critical,CA:true"));
            extList.Add(new X509V3ExtensionValue("keyUsage", false, "cRLSign,keyCertSign"));

            DateTime start = DateTime.Now;
            DateTime end = start + TimeSpan.FromMinutes(10);
            CryptoKey key = new CryptoKey(new DSA(true));
            using (X509Certificate cert = new X509Certificate(101, "CN=Root", "CN=Root", key, start, end)) {
                foreach (X509V3ExtensionValue extValue in extList) {
                    using (X509Extension ext = new X509Extension(cert, cert, extValue.Name, extValue.IsCritical, extValue.Value)) {
                        cert.AddExtension(ext);
                    }
                }

                foreach (X509Extension ext in cert.Extensions) {
                    Console.WriteLine(ext);
                }

                Assert.AreEqual(extList.Count, cert.Extensions.Count);
            }
        }
 public void Bug3017248()
 {
     CryptoKey key = new CryptoKey(new DSA(true));
     BIO output = BIO.MemoryBuffer();
     key.WritePrivateKey(output, Cipher.Null, "password");
     output.SetClose(BIO.CloseOption.Close);
     Console.WriteLine(output.ReadString());
 }
		static TestCipher()
		{
			const int numKeys = 10;
			Keys = new CryptoKey[numKeys];
			for (int i = 0; i < numKeys; i++)
			{
				using (var rsa = new RSA())
				{
					rsa.GenerateKeys(1024, BigNumber.One, null, null);
					Keys[i] = new CryptoKey(rsa);
				}
			}
		}
		public void CanCompareDSA()
		{
			using (var dsa = new DSA(true))
			using (var lhs = new CryptoKey(dsa))
			{
				Assert.AreEqual(lhs, lhs);
				using (var rhs = new CryptoKey(dsa))
				{
					Assert.AreEqual(lhs, rhs);
				}

				using (var dsa2 = new DSA(true))
				using (var other = new CryptoKey(dsa2))
				{
					Assert.AreNotEqual(lhs, other);
				}
			}
		}
Beispiel #9
0
        private static X509Certificate CreateCertificate()
        {
            BigNumber bn = 0x10001;
            var rsa = new RSA();
            rsa.GenerateKeys(2048, bn, null, null);
            var key = new CryptoKey(rsa);

            var cert = new X509Certificate(
                new SimpleSerialNumber().Next(),
                new X509Name("Mooege"),
                new X509Name("Mooege"),
                key,
                DateTime.Now,
                DateTime.Now + TimeSpan.FromDays(365));

            cert.PrivateKey = key;
            return cert;
        }
Beispiel #10
0
		X509Certificate CreateCertificate(X509CertificateAuthority ca, string name, Configuration cfg, string section)
		{
			var now = DateTime.Now;
			var future = now + TimeSpan.FromDays(365);

			using (var subject = new X509Name(name))
			using (var rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (var key = new CryptoKey(rsa))
				{
					var request = new X509Request(1, subject, key);
					var cert = ca.ProcessRequest(request, now, future, cfg, section);
					cert.PrivateKey = key;
					return cert;
				}
			}
		}
Beispiel #11
0
		public void CanCompare()
		{
			using (DSA dsa = new DSA(true))
			{
				using (CryptoKey lhs = new CryptoKey(dsa))
				{
					Assert.AreEqual(lhs, lhs);
					using (CryptoKey rhs = new CryptoKey(dsa))
					{
						Assert.AreEqual(lhs, rhs);
					}

					using (DSA dsa2 = new DSA(true))
					{
						using (CryptoKey other = new CryptoKey(dsa2))
						{
							Assert.IsFalse(lhs == other);
						}
					}
				}
			}

			using (RSA rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (CryptoKey lhs = new CryptoKey(rsa))
				{
					Assert.AreEqual(lhs, lhs);
					using (CryptoKey rhs = new CryptoKey(rsa))
					{
						Assert.AreEqual(lhs, rhs);
					}

					using (RSA rsa2 = new RSA())
					{
						rsa2.GenerateKeys(1024, BigNumber.One, null, null);
						using (CryptoKey other = new CryptoKey(rsa2))
						{
							Assert.IsFalse(lhs == other);
						}
					}
				}
			}
		}
		public void CanCompareRSA()
		{
			using (var rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (var lhs = new CryptoKey(rsa))
				{
					Assert.AreEqual(lhs, lhs);
					using (var rhs = new CryptoKey(rsa))
					{
						Assert.AreEqual(lhs, rhs);
					}

					using (var rsa2 = new RSA())
					{
						rsa2.GenerateKeys(1024, BigNumber.One, null, null);
						using (var other = new CryptoKey(rsa2))
						{
							Assert.AreNotEqual(lhs, other);
						}
					}
				}
			}
		}
Beispiel #13
0
		/// <summary>
		/// Calls EVP_SignFinal()
		/// </summary>
		/// <param name="md"></param>
		/// <param name="bio"></param>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public static byte[] Sign(MessageDigest md, BIO bio, CryptoKey pkey)
		{
			BIO bmd = BIO.MessageDigest(md);
			bmd.Push(bio);

			while (true)
			{
				ArraySegment<byte> bytes = bmd.ReadBytes(1024 * 4);
				if (bytes.Count == 0)
					break;
			}

			MessageDigestContext ctx = new MessageDigestContext(bmd);

			byte[] sig = new byte[pkey.Size];
			uint len = (uint)sig.Length;
			Native.ExpectSuccess(Native.EVP_SignFinal(ctx.Handle, sig, ref len, pkey.Handle));
			byte[] ret = new byte[len];
			Buffer.BlockCopy(sig, 0, ret, 0, (int)len);
			return ret;
		}
Beispiel #14
0
		/// <summary>
		/// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_SignFinal()
		/// </summary>
		/// <param name="msg"></param>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public byte[] Sign(byte[] msg, CryptoKey pkey) 
		{
			byte[] sig = new byte[pkey.Size];
			uint len = (uint)sig.Length;
			Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero));
			Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length));
			Native.ExpectSuccess(Native.EVP_SignFinal(this.ptr, sig, ref len, pkey.Handle));
			byte[] ret = new byte[len];
			Buffer.BlockCopy(sig, 0, ret, 0, (int)len);
			return ret;
		}
Beispiel #15
0
		/// <summary>
		/// Calls EVP_OpenInit() and EVP_OpenFinal()
		/// </summary>
		/// <param name="input"></param>
		/// <param name="ekey"></param>
		/// <param name="iv"></param>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public byte[] Open(byte[] input, byte[] ekey, byte[] iv, CryptoKey pkey) 
		{
			Native.ExpectSuccess(Native.EVP_OpenInit(
				this.ptr, this.cipher.Handle, ekey, ekey.Length, iv, pkey.Handle));
			
			MemoryStream memory = new MemoryStream();
			byte[] output = new byte[input.Length + this.Cipher.BlockSize]; 
			int len;
			
			Native.ExpectSuccess(Native.EVP_DecryptUpdate(this.ptr, output, out len, input, input.Length));
			memory.Write(output, 0, len);
			
			Native.ExpectSuccess(Native.EVP_OpenFinal(this.ptr, output, out len));
			memory.Write(output, 0, len);

			return memory.ToArray();
		}
Beispiel #16
0
		public void CanCreateFromDH()
		{
			using (DH dh = new DH())
			{
				dh.GenerateKeys();
				using (CryptoKey key = new CryptoKey(dh)) {
					Assert.AreEqual(CryptoKey.KeyType.DH, key.Type);
				}
			}
		}
Beispiel #17
0
		public void CanCreateFromDSA()
		{
			using (DSA dsa = new DSA(true))
			{
				using (CryptoKey key = new CryptoKey(dsa))
				{
					Assert.AreEqual(CryptoKey.KeyType.DSA, key.Type);
					Assert.AreEqual(dsa.Size, key.Size);
				}
			}

			using (CryptoKey key = new CryptoKey(new DSA(false)))
			{
				Assert.AreEqual(CryptoKey.KeyType.DSA, key.Type);
			}
		}
Beispiel #18
0
		/// <summary>
		/// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_VerifyFinal()
		/// </summary>
		/// <param name="msg"></param>
		/// <param name="sig"></param>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public bool Verify(byte[] msg, byte[] sig, CryptoKey pkey) 
		{
			Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero));
			Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length));
			int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(this.ptr, sig, (uint)sig.Length, pkey.Handle));
			return ret == 1;
		}
Beispiel #19
0
		/// <summary>
		/// Calls EVP_VerifyFinal()
		/// </summary>
		/// <param name="md"></param>
		/// <param name="bio"></param>
		/// <param name="sig"></param>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public static bool Verify(MessageDigest md, BIO bio, byte[] sig, CryptoKey pkey)
		{
			BIO bmd = BIO.MessageDigest(md);
			bmd.Push(bio);

			while (true)
			{
				ArraySegment<byte> bytes = bmd.ReadBytes(1024 * 4);
				if (bytes.Count == 0)
					break;
			}

			MessageDigestContext ctx = new MessageDigestContext(bmd);

			int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(ctx.Handle, sig, (uint)sig.Length, pkey.Handle));
			return ret == 1;
		}
		/// <summary>
		/// Factory method that creates a X509CertificateAuthority instance with
		/// an internal self signed certificate. This method allows creation without
		/// the need for the Configuration file, X509V3Extensions may be added
		/// with the X509V3ExtensionList parameter
		/// </summary>
		/// <param name="seq"></param>
		/// <param name="key"></param>
		/// <param name="digest"></param>
		/// <param name="subject"></param>
		/// <param name="start"></param>
		/// <param name="validity"></param>
		/// <param name="extensions"></param>
		/// <returns></returns>
		public static X509CertificateAuthority SelfSigned(
			ISequenceNumber seq,
			CryptoKey key,
			MessageDigest digest,
			X509Name subject,
			DateTime start,
			TimeSpan validity,
			IEnumerable<X509V3ExtensionValue> extensions)
		{
			var cert = new X509Certificate(
				           seq.Next(),
				           subject,
				           subject,
				           key,
				           start,
				           start + validity);

			if (extensions != null)
			{
				foreach (var extValue in extensions)
				{
					using (var ext = new X509Extension(cert, cert, extValue.Name, extValue.IsCritical, extValue.Value))
					{
						cert.AddExtension(ext);
					}
				}
			}

			cert.Sign(key, digest);

			return new X509CertificateAuthority(cert, key, seq);
		}
Beispiel #21
0
		public void CanCreateFromRSA()
		{
			using (RSA rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (CryptoKey key = new CryptoKey(rsa))
				{
					Assert.AreEqual(CryptoKey.KeyType.RSA, key.Type);
					Assert.AreEqual(rsa.Size, key.Size);
				}
			}
		}
		/// <summary>
		/// Constructs a X509CertifcateAuthority with the specified parameters.
		/// </summary>
		/// <param name="caCert"></param>
		/// <param name="caKey"></param>
		/// <param name="serial"></param>
		public X509CertificateAuthority(X509Certificate caCert, CryptoKey caKey, ISequenceNumber serial)
		{
			if (!caCert.CheckPrivateKey(caKey))
				throw new Exception("The specified CA Private Key does match the specified CA Certificate");

			this.caCert = caCert;
			this.caKey = caKey;
			this.serial = serial;
		}
Beispiel #23
0
		public void CanCreateAndDispose()
		{
			using (CryptoKey key = new CryptoKey())
			{
			}
		}
Beispiel #24
0
		/// <summary>
		/// Calls EVP_OpenInit() and EVP_OpenFinal()
		/// </summary>
		/// <param name="input"></param>
		/// <param name="iv"></param>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public byte[] Open(byte[] input, byte[] iv, CryptoKey pkey) 
		{
			Native.ExpectSuccess(Native.EVP_OpenInit(
				this.ptr, this.cipher.Handle, input, input.Length, iv, pkey.Handle));

			int len;
			Native.ExpectSuccess(Native.EVP_OpenFinal(this.ptr, null, out len));

			byte[] output = new byte[len];
			Native.ExpectSuccess(Native.EVP_OpenFinal(this.ptr, output, out len));

			return output;
		}
Beispiel #25
0
 public int UsePrivateKey(CryptoKey key)
 {
     return Native.ExpectSuccess(Native.SSL_CTX_use_PrivateKey(this.ptr, key.Handle));
 }
Beispiel #26
0
		/// <summary>
		/// Calls EVP_SealInit() and EVP_SealFinal()
		/// </summary>
		/// <param name="pkeys"></param>
		/// <param name="needsIV"></param>
		/// <returns></returns>
		public Envelope Seal(CryptoKey[] pkeys, bool needsIV) 
		{
			Envelope ret = new Envelope();
			byte[][] bufs = new byte[pkeys.Length][];
			int[] lens = new int[pkeys.Length];
			IntPtr[] pubkeys = new IntPtr[pkeys.Length];
			ret.Keys = new ArraySegment<byte>[pkeys.Length];
			for (int i = 0; i < pkeys.Length; ++i)
			{
				bufs[i] = new byte[pkeys[i].Size];
				lens[i] = pkeys[i].Size;
				pubkeys[i] = pkeys[i].Handle;
			}

			if(needsIV)
				ret.IV = new byte[this.cipher.IVLength];

			int len;
			Native.ExpectSuccess(Native.EVP_SealInit(
				this.ptr, this.cipher.Handle, bufs, lens, ret.IV, pubkeys, pubkeys.Length));
			for (int i = 0; i < pkeys.Length; ++i)
			{
				ret.Keys[i] = new ArraySegment<byte>(bufs[i], 0, lens[i]);
			}

			Native.ExpectSuccess(Native.EVP_SealFinal(this.ptr, null, out len));

			ret.Data = new byte[len];
			Native.ExpectSuccess(Native.EVP_SealFinal(this.ptr, ret.Data, out len));

			return ret;
		}
Beispiel #27
0
		public int InternalClientCertificateSelectionCallback(Ssl ssl, out X509Certificate x509_cert, out CryptoKey key)
		{
			int nRet = 0;
			x509_cert = null;
			key = null;

			Core.Stack<X509Name> name_stack = ssl.CAList;
			string[] strIssuers = new string[name_stack.Count];
			int count = 0;

			foreach (X509Name name in name_stack)
			{
				strIssuers[count++] = name.OneLine;
			}

			if (localCertificateSelectionCallback != null)
			{
				X509Certificate cert = localCertificateSelectionCallback(this, targetHost, clientCertificates, ssl.GetPeerCertificate(), strIssuers);
				if (cert != null && cert.HasPrivateKey)
				{
					x509_cert = cert;
					key = cert.PrivateKey;
					// Addref the cert and private key
					x509_cert.AddRef();
					key.AddRef();
					// return success
					nRet = 1;
				}
			}

			return nRet;
		}
Beispiel #28
0
		/// <summary>
		/// Calls EVP_SignFinal()
		/// </summary>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public byte[] SignFinal(CryptoKey pkey)
		{
			byte[] digest = new byte[this.md.Size];
			byte[] sig = new byte[pkey.Size];
			uint len = (uint)sig.Length;
			Native.ExpectSuccess(Native.EVP_SignFinal(this.ptr, sig, ref len, pkey.Handle));
			return sig;
		}
Beispiel #29
0
		/// <summary>
		/// Calls EVP_SealInit() and EVP_SealFinal()
		/// </summary>
		/// <param name="pkeys"></param>
		/// <param name="input"></param>
		/// <returns></returns>
		public Envelope Seal(CryptoKey[] pkeys, byte[] input)
		{
			Envelope env = new Envelope();
			
			var ptrs = new IntPtr[pkeys.Length];
			try {
				env.Keys = new byte[pkeys.Length][];
				IntPtr[] pubkeys = new IntPtr[pkeys.Length];
				int[] ekeylens =  new int[pkeys.Length];

				for (int i = 0; i < pkeys.Length; i++) {
					ptrs[i] = Marshal.AllocHGlobal(pkeys[i].Size);
					pubkeys[i] = pkeys[i].Handle;
				}
				
				if (this.Cipher.IVLength > 0) {
					env.IV = new byte[this.Cipher.IVLength];
				}
			
				Native.ExpectSuccess(Native.EVP_SealInit(
					this.ptr, this.Cipher.Handle, ptrs, ekeylens, env.IV, pubkeys, pubkeys.Length));

				for (int i = 0; i < pkeys.Length; i++) {
					env.Keys[i] = new byte[ekeylens[i]];
					Marshal.Copy(ptrs[i], env.Keys[i], 0, ekeylens[i]);
				}
	
				MemoryStream memory = new MemoryStream();
				byte[] output = new byte[input.Length + this.Cipher.BlockSize];
	
				int len;
				Native.ExpectSuccess(Native.EVP_EncryptUpdate(this.ptr, output, out len, input, input.Length));
				memory.Write(output, 0, len);
				
				Native.ExpectSuccess(Native.EVP_SealFinal(this.ptr, output, out len));
				memory.Write(output, 0, len);
				
				env.Data = memory.ToArray();

				return env;
			}
			finally {
				foreach (var ptr in ptrs) {
					Marshal.FreeHGlobal(ptr);
				}
			}
		}
Beispiel #30
0
		/// <summary>
		/// Calls EVP_VerifyFinal()
		/// </summary>
		/// <param name="sig"></param>
		/// <param name="pkey"></param>
		/// <returns></returns>
		public bool VerifyFinal(byte[] sig, CryptoKey pkey)
		{
			int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(this.ptr, sig, (uint)sig.Length, pkey.Handle));
			return ret == 1;
		}