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 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}\tIssuert 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 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 (" -ic cert\tTake the issuer's name from the specified certificate.");
57 Console.WriteLine (" -in name\tTake the issuer's name from the specified parameter.");
58 Console.WriteLine (" -iv pvkfile\tSign the certificate using the private key inside the PVK file.");
59 Console.WriteLine (" -m number\tCertificate validity period (in months).");
60 Console.WriteLine (" -sv pvkfile\tCreate a new PVK file if non-existant, otherwise use the PVK file as the subject public key.");
61 Console.WriteLine (" -?\thelp (display basic message)");
64 static X509Certificate LoadCertificate (string filename)
66 FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);
67 byte[] rawcert = new byte [fs.Length];
68 fs.Read (rawcert, 0, rawcert.Length);
70 return new X509Certificate (rawcert);
73 static void WriteCertificate (string filename, byte[] rawcert)
75 FileStream fs = File.Open (filename, FileMode.Create, FileAccess.Write);
76 fs.Write (rawcert, 0, rawcert.Length);
80 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>";
82 static string defaultIssuer = "CN=Mono Test Root Agency";
83 static string defaultSubject = "CN=Poupou's-Software-Factory";
86 static int Main (string[] args)
88 if (args.Length < 1) {
90 Console.WriteLine ("ERROR: Missing output filename {0}", Environment.NewLine);
95 string fileName = args [args.Length - 1];
98 byte[] sn = Guid.NewGuid ().ToByteArray ();
99 string subject = defaultSubject;
100 string issuer = defaultIssuer;
101 DateTime notBefore = DateTime.Now;
102 DateTime notAfter = new DateTime (643445675990000000); // 12/31/2039 23:59:59Z
104 RSA issuerKey = (RSA)RSA.Create ();
105 issuerKey.FromXmlString (MonoTestRootAgency);
106 RSA subjectKey = (RSA)RSA.Create ();
108 bool selfSigned = false;
109 string hashName = "MD5";
111 CspParameters subjectParams = new CspParameters ();
112 CspParameters issuerParams = new CspParameters ();
113 BasicConstraintsExtension bce = null;
114 ExtendedKeyUsageExtension eku = null;
119 while (i < args.Length) {
120 switch (args [i++]) {
124 sn = BitConverter.GetBytes (Convert.ToInt32 (args [i++]));
127 // Subject Distinguish Name
128 subject = args [i++];
131 // (authenticode) commercial or individual
132 // CRITICAL KeyUsageRestriction extension
134 string usageRestriction = args [i++].ToLower ();
135 switch (usageRestriction) {
138 Console.WriteLine ("WARNING: Unsupported deprecated certification extension KeyUsageRestriction not included");
139 // Console.WriteLine ("WARNING: ExtendedKeyUsage for codesigning has been included.");
142 Console.WriteLine ("Unsupported restriction " + usageRestriction);
149 switch (args [i++].ToLower ()) {
157 Console.WriteLine ("Unsupported hash algorithm");
162 // Validity / notBefore
163 notBefore = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
166 // basic constraints - autority or end-entity
167 switch (args [i++].ToLower ()) {
170 bce = new BasicConstraintsExtension ();
171 bce.CertificateAuthority = true;
174 // do not include extension
178 Console.WriteLine ("ERROR: No more supported in X.509");
181 Console.WriteLine ("Unsupported certificate type");
186 // CN private extension ?
187 Console.WriteLine ("Unsupported option");
190 // Validity / notAfter
191 notAfter = DateTime.Parse (args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
194 // extendedKeyUsage extension
195 char[] sep = { ',' };
196 string[] purposes = args [i++].Split (sep);
198 eku = new ExtendedKeyUsageExtension ();
199 foreach (string purpose in purposes) {
200 eku.KeyPurpose.Add (purpose);
204 // pathLength (basicConstraints)
205 // MS use an old basicConstrains (2.5.29.10) which
206 // allows both CA and End-Entity. This is no
207 // more supported with 2.5.29.19.
209 bce = new BasicConstraintsExtension ();
210 bce.CertificateAuthority = true;
212 bce.PathLenConstraint = Convert.ToInt32 (args [i++]);
215 X509Certificate x509 = LoadCertificate (args [i++]);
216 issuer = x509.SubjectName;
223 PrivateKey pvk = PrivateKey.CreateFromFile (args [i++]);
228 // spcSpAgencyInfo private extension
229 Console.WriteLine ("Unsupported option");
232 // validity period (in months)
233 notAfter = notBefore.AddMonths (Convert.ToInt32 (args [i++]));
236 // Netscape's private extensions - NetscapeCertType
237 // BasicContraints - End Entity
238 Console.WriteLine ("Unsupported option");
244 // subject certificate ? renew ?
245 Console.WriteLine ("Unsupported option");
247 // Issuer CspParameters options
249 issuerParams.KeyContainerName = args [i++];
252 // select a key in the provider
253 string ikn = args [i++].ToLower ();
256 issuerParams.KeyNumber = 0;
259 issuerParams.KeyNumber = 1;
262 issuerParams.KeyNumber = Convert.ToInt32 (ikn);
267 issuerParams.ProviderName = args [i++];
270 switch (args [i++].ToLower ()) {
272 issuerParams.Flags = CspProviderFlags.UseMachineKeyStore;
275 issuerParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
278 Console.WriteLine ("Unknown key store for issuer");
283 Console.WriteLine ("Unsupported option");
286 issuerParams.ProviderType = Convert.ToInt32 (args [i++]);
288 // Subject CspParameters Options
290 subjectParams.KeyContainerName = args [i++];
293 // select a key in the provider
294 string skn = args [i++].ToLower ();
297 subjectParams.KeyNumber = 0;
300 subjectParams.KeyNumber = 1;
303 subjectParams.KeyNumber = Convert.ToInt32 (skn);
308 subjectParams.ProviderName = args [i++];
311 switch (args [i++].ToLower ()) {
313 subjectParams.Flags = CspProviderFlags.UseMachineKeyStore;
316 subjectParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
319 Console.WriteLine ("Unknown key store for subject");
324 Console.WriteLine ("Unsupported option");
327 string pvkFile = args [i++];
328 if (File.Exists (pvkFile)) {
329 PrivateKey key = PrivateKey.CreateFromFile (pvkFile);
330 subjectKey = key.RSA;
333 PrivateKey key = new PrivateKey ();
334 key.RSA = subjectKey;
339 subjectParams.ProviderType = Convert.ToInt32 (args [i++]);
349 if (i != args.Length) {
350 Console.WriteLine ("ERROR: Unknown parameter");
358 // serial number MUST be positive
359 if ((sn [0] & 0x80) == 0x80)
363 if (subject != defaultSubject) {
365 issuerKey = subjectKey;
369 subjectKey = issuerKey;
374 throw new Exception ("Missing Subject Name");
376 X509CertificateBuilder cb = new X509CertificateBuilder (3);
377 cb.SerialNumber = sn;
378 cb.IssuerName = issuer;
379 cb.NotBefore = notBefore;
380 cb.NotAfter = notAfter;
381 cb.SubjectName = subject;
382 cb.SubjectPublicKey = subjectKey;
385 cb.Extensions.Add (bce);
387 cb.Extensions.Add (eku);
390 byte[] rawcert = cb.Sign (issuerKey);
391 WriteCertificate (fileName, rawcert);
392 Console.WriteLine ("Success");
395 catch (Exception e) {
396 Console.WriteLine ("ERROR: " + e.ToString ());