2 // makecert.cs: makecert clone tool
5 // Sebastien Pouliot <sebastien@ximian.com>
7 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
12 using System.Globalization;
14 using System.Reflection;
15 using System.Security.Cryptography;
17 using Mono.Security.Authenticode;
18 using Mono.Security.X509;
19 using Mono.Security.X509.Extensions;
21 [assembly: AssemblyTitle("Mono MakeCert")]
22 [assembly: AssemblyDescription("X.509 Certificate Builder")]
24 namespace Mono.Tools {
28 static private void Header ()
30 Console.WriteLine (new AssemblyInfo ().ToString ());
33 static private void Help ()
35 Console.WriteLine ("Usage: makecert [options] certificate{0}", Environment.NewLine);
36 Console.WriteLine (" -# num{0}\tCertificate serial number", Environment.NewLine);
37 Console.WriteLine (" -n dn{0}\tSubject Distinguished Name", Environment.NewLine);
38 Console.WriteLine (" -in dn{0}\tIssuer Distinguished Name", Environment.NewLine);
39 Console.WriteLine (" -r{0}\tCreate a self-signed (root) certificate", Environment.NewLine);
40 Console.WriteLine (" -sv pkvfile{0}\tPrivate key file (.PVK) for the subject (created if missing)", Environment.NewLine);
41 Console.WriteLine (" -iv pvkfile{0}\tPrivate key file (.PVK) for the issuer", Environment.NewLine);
42 Console.WriteLine (" -ic certfile{0}\tExtract the issuer's name from the specified certificate", Environment.NewLine);
43 Console.WriteLine (" -?{0}\thelp (display this help message)", Environment.NewLine);
44 Console.WriteLine (" -!{0}\textended help (for advanced options)", Environment.NewLine);
47 static private void ExtendedHelp ()
49 Console.WriteLine ("Usage: makecert [options] certificate{0}", Environment.NewLine);
50 Console.WriteLine (" -a hash\tSelect hash algorithm. Only MD5 and SHA1 (default) are supported.");
51 Console.WriteLine (" -b date\tThe date since when the certificate is valid (notBefore).");
52 Console.WriteLine (" -cy [authority|end]\tBasic constraints. Select Authority or End-Entity certificate.");
53 Console.WriteLine (" -e date\tThe date until when the certificate is valid (notAfter).");
54 Console.WriteLine (" -eku oid[,oid]\tAdd some extended key usage OID to the certificate.");
55 Console.WriteLine (" -h number\tAdd a path length restriction to the certificate chain.");
56 Console.WriteLine (" -in name\tTake the issuer's name from the specified parameter.");
57 Console.WriteLine (" -m number\tCertificate validity period (in months).");
58 Console.WriteLine (" -p12 pkcs12file password\tCreate a new PKCS#12 file with the specified password.");
59 Console.WriteLine (" -?\thelp (display basic message)");
62 static X509Certificate LoadCertificate (string filename)
64 FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);
65 byte[] rawcert = new byte [fs.Length];
66 fs.Read (rawcert, 0, rawcert.Length);
68 return new X509Certificate (rawcert);
71 static void WriteCertificate (string filename, byte[] rawcert)
73 FileStream fs = File.Open (filename, FileMode.Create, FileAccess.Write);
74 fs.Write (rawcert, 0, rawcert.Length);
78 static string MonoTestRootAgency = "<RSAKeyValue><Modulus>v/4nALBxCE+9JgEC0LnDUvKh6e96PwTpN4Rj+vWnqKT7IAp1iK/JjuqvAg6DQ2vTfv0dTlqffmHH51OyioprcT5nzxcSTsZb/9jcHScG0s3/FRIWnXeLk/fgm7mSYhjUaHNI0m1/NTTktipicjKxo71hGIg9qucCWnDum+Krh/k=</Modulus><Exponent>AQAB</Exponent><P>9jbKxMXEruW2CfZrzhxtull4O8P47+mNsEL+9gf9QsRO1jJ77C+jmzfU6zbzjf8+ViK+q62tCMdC1ZzulwdpXQ==</P><Q>x5+p198l1PkK0Ga2mRh0SIYSykENpY2aLXoyZD/iUpKYAvATm0/wvKNrE4dKJyPCA+y3hfTdgVag+SP9avvDTQ==</Q><DP>ISSjCvXsUfbOGG05eddN1gXxL2pj+jegQRfjpk7RAsnWKvNExzhqd5x+ZuNQyc6QH5wxun54inP4RTUI0P/IaQ==</DP><DQ>R815VQmR3RIbPqzDXzv5j6CSH6fYlcTiQRtkBsUnzhWmkd/y3XmamO+a8zJFjOCCx9CcjpVuGziivBqi65lVPQ==</DQ><InverseQ>iYiu0KwMWI/dyqN3RJYUzuuLj02/oTD1pYpwo2rvNCXU1Q5VscOeu2DpNg1gWqI+1RrRCsEoaTNzXB1xtKNlSw==</InverseQ><D>nIfh1LYF8fjRBgMdAH/zt9UKHWiaCnc+jXzq5tkR8HVSKTVdzitD8bl1JgAfFQD8VjSXiCJqluexy/B5SGrCXQ49c78NIQj0hD+J13Y8/E0fUbW1QYbhj6Ff7oHyhaYe1WOQfkp2t/h+llHOdt1HRf7bt7dUknYp7m8bQKGxoYE=</D></RSAKeyValue>";
80 static string defaultIssuer = "CN=Mono Test Root Agency";
81 static string defaultSubject = "CN=Poupou's-Software-Factory";
84 static int Main (string[] args)
86 if (args.Length < 1) {
88 Console.WriteLine ("ERROR: Missing output filename {0}", Environment.NewLine);
93 string fileName = args [args.Length - 1];
96 byte[] sn = Guid.NewGuid ().ToByteArray ();
97 string subject = defaultSubject;
98 string issuer = defaultIssuer;
99 DateTime notBefore = DateTime.Now;
100 DateTime notAfter = new DateTime (643445675990000000); // 12/31/2039 23:59:59Z
102 RSA issuerKey = (RSA)RSA.Create ();
103 issuerKey.FromXmlString (MonoTestRootAgency);
104 RSA subjectKey = (RSA)RSA.Create ();
106 bool selfSigned = false;
107 string hashName = "SHA1";
109 CspParameters subjectParams = new CspParameters ();
110 CspParameters issuerParams = new CspParameters ();
111 BasicConstraintsExtension bce = null;
112 ExtendedKeyUsageExtension eku = null;
113 string p12file = null;
114 string p12pwd = null;
115 X509Certificate issuerCertificate = null;
120 while (i < args.Length) {
121 switch (args [i++]) {
125 sn = BitConverter.GetBytes (Convert.ToInt32 (args [i++]));
128 // Subject Distinguish Name
129 subject = args [i++];
132 // (authenticode) commercial or individual
133 // CRITICAL KeyUsageRestriction extension
135 string usageRestriction = args [i++].ToLower ();
136 switch (usageRestriction) {
139 Console.WriteLine ("WARNING: Unsupported deprecated certification extension KeyUsageRestriction not included");
140 // Console.WriteLine ("WARNING: ExtendedKeyUsage for codesigning has been included.");
143 Console.WriteLine ("Unsupported restriction " + usageRestriction);
150 switch (args [i++].ToLower ()) {
155 Console.WriteLine ("WARNING: MD5 is no more safe for this usage.");
159 Console.WriteLine ("Unsupported hash algorithm");
164 // Validity / notBefore
165 notBefore = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
168 // basic constraints - autority or end-entity
169 switch (args [i++].ToLower ()) {
172 bce = new BasicConstraintsExtension ();
173 bce.CertificateAuthority = true;
176 // do not include extension
180 Console.WriteLine ("ERROR: No more supported in X.509");
183 Console.WriteLine ("Unsupported certificate type");
188 // CN private extension ?
189 Console.WriteLine ("Unsupported option");
192 // Validity / notAfter
193 notAfter = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
196 // extendedKeyUsage extension
197 char[] sep = { ',' };
198 string[] purposes = args [i++].Split (sep);
200 eku = new ExtendedKeyUsageExtension ();
201 foreach (string purpose in purposes) {
202 eku.KeyPurpose.Add (purpose);
206 // pathLength (basicConstraints)
207 // MS use an old basicConstrains (2.5.29.10) which
208 // allows both CA and End-Entity. This is no
209 // more supported with 2.5.29.19.
211 bce = new BasicConstraintsExtension ();
212 bce.CertificateAuthority = true;
214 bce.PathLenConstraint = Convert.ToInt32 (args [i++]);
217 issuerCertificate = LoadCertificate (args [i++]);
218 issuer = issuerCertificate.SubjectName;
225 PrivateKey pvk = PrivateKey.CreateFromFile (args [i++]);
230 // spcSpAgencyInfo private extension
231 Console.WriteLine ("Unsupported option");
234 // validity period (in months)
235 notAfter = notBefore.AddMonths (Convert.ToInt32 (args [i++]));
238 // Netscape's private extensions - NetscapeCertType
239 // BasicContraints - End Entity
240 Console.WriteLine ("Unsupported option");
246 // subject certificate ? renew ?
247 Console.WriteLine ("Unsupported option");
249 // Issuer CspParameters options
251 issuerParams.KeyContainerName = args [i++];
254 // select a key in the provider
255 string ikn = args [i++].ToLower ();
258 issuerParams.KeyNumber = 0;
261 issuerParams.KeyNumber = 1;
264 issuerParams.KeyNumber = Convert.ToInt32 (ikn);
269 issuerParams.ProviderName = args [i++];
272 switch (args [i++].ToLower ()) {
274 issuerParams.Flags = CspProviderFlags.UseMachineKeyStore;
277 issuerParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
280 Console.WriteLine ("Unknown key store for issuer");
285 Console.WriteLine ("Unsupported option");
288 issuerParams.ProviderType = Convert.ToInt32 (args [i++]);
290 // Subject CspParameters Options
292 subjectParams.KeyContainerName = args [i++];
295 // select a key in the provider
296 string skn = args [i++].ToLower ();
299 subjectParams.KeyNumber = 0;
302 subjectParams.KeyNumber = 1;
305 subjectParams.KeyNumber = Convert.ToInt32 (skn);
310 subjectParams.ProviderName = args [i++];
313 switch (args [i++].ToLower ()) {
315 subjectParams.Flags = CspProviderFlags.UseMachineKeyStore;
318 subjectParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
321 Console.WriteLine ("Unknown key store for subject");
326 Console.WriteLine ("Unsupported option");
329 string pvkFile = args [i++];
330 if (File.Exists (pvkFile)) {
331 PrivateKey key = PrivateKey.CreateFromFile (pvkFile);
332 subjectKey = key.RSA;
335 PrivateKey key = new PrivateKey ();
336 key.RSA = subjectKey;
341 subjectParams.ProviderType = Convert.ToInt32 (args [i++]);
343 // Mono Specific Options
345 p12file = args [i++];
356 if (i != args.Length) {
357 Console.WriteLine ("ERROR: Unknown parameter");
365 // serial number MUST be positive
366 if ((sn [0] & 0x80) == 0x80)
370 if (subject != defaultSubject) {
372 issuerKey = subjectKey;
376 subjectKey = issuerKey;
381 throw new Exception ("Missing Subject Name");
383 X509CertificateBuilder cb = new X509CertificateBuilder (3);
384 cb.SerialNumber = sn;
385 cb.IssuerName = issuer;
386 cb.NotBefore = notBefore;
387 cb.NotAfter = notAfter;
388 cb.SubjectName = subject;
389 cb.SubjectPublicKey = subjectKey;
392 cb.Extensions.Add (bce);
394 cb.Extensions.Add (eku);
397 byte[] rawcert = cb.Sign (issuerKey);
399 if (p12file == null) {
400 WriteCertificate (fileName, rawcert);
402 PKCS12 p12 = new PKCS12 ();
403 p12.Password = p12pwd;
404 p12.AddCertificate (new X509Certificate (rawcert));
405 if (issuerCertificate != null)
406 p12.AddCertificate (issuerCertificate);
407 p12.AddPkcs8ShroudedKeyBag (subjectKey);
408 p12.SaveToFile (p12file);
410 Console.WriteLine ("Success");
413 catch (Exception e) {
414 Console.WriteLine ("ERROR: " + e.ToString ());