Merge "chg: format show history link"
[gigi.git] / util-testing / club / wpia / gigi / util / SimpleSigner.java
1 package club.wpia.gigi.util;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
11 import java.io.PrintWriter;
12 import java.io.Reader;
13 import java.math.BigInteger;
14 import java.nio.file.Paths;
15 import java.security.GeneralSecurityException;
16 import java.security.KeyFactory;
17 import java.security.NoSuchAlgorithmException;
18 import java.security.PrivateKey;
19 import java.security.PublicKey;
20 import java.security.Signature;
21 import java.security.cert.CertificateFactory;
22 import java.security.cert.X509Certificate;
23 import java.security.spec.InvalidKeySpecException;
24 import java.security.spec.PKCS8EncodedKeySpec;
25 import java.sql.SQLException;
26 import java.sql.Timestamp;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.Base64;
30 import java.util.Calendar;
31 import java.util.Date;
32 import java.util.GregorianCalendar;
33 import java.util.HashMap;
34 import java.util.LinkedList;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Properties;
39 import java.util.TimeZone;
40
41 import javax.security.auth.x500.X500Principal;
42
43 import club.wpia.gigi.GigiApiException;
44 import club.wpia.gigi.crypto.SPKAC;
45 import club.wpia.gigi.database.DatabaseConnection;
46 import club.wpia.gigi.database.DatabaseConnection.Link;
47 import club.wpia.gigi.database.GigiPreparedStatement;
48 import club.wpia.gigi.database.GigiResultSet;
49 import club.wpia.gigi.dbObjects.Certificate;
50 import club.wpia.gigi.dbObjects.Certificate.AttachmentType;
51 import club.wpia.gigi.dbObjects.Certificate.CSRType;
52 import club.wpia.gigi.dbObjects.Certificate.SANType;
53 import club.wpia.gigi.dbObjects.Certificate.SubjectAlternateName;
54 import club.wpia.gigi.dbObjects.CertificateProfile;
55 import club.wpia.gigi.dbObjects.Digest;
56 import club.wpia.gigi.output.DateSelector;
57 import club.wpia.gigi.util.ServerConstants.Host;
58 import sun.security.pkcs10.PKCS10;
59 import sun.security.util.DerOutputStream;
60 import sun.security.util.DerValue;
61 import sun.security.util.ObjectIdentifier;
62 import sun.security.x509.AVA;
63 import sun.security.x509.AlgorithmId;
64 import sun.security.x509.GeneralNameInterface;
65 import sun.security.x509.RDN;
66 import sun.security.x509.X500Name;
67
68 public class SimpleSigner {
69
70     private static GigiPreparedStatement warnMail;
71
72     private static GigiPreparedStatement updateMail;
73
74     private static GigiPreparedStatement readyCerts;
75
76     private static GigiPreparedStatement getSANSs;
77
78     private static GigiPreparedStatement revoke;
79
80     private static GigiPreparedStatement revokeCompleted;
81
82     private static GigiPreparedStatement finishJob;
83
84     private static GigiPreparedStatement locateCA;
85
86     private static volatile boolean running = true;
87
88     private static Thread runner;
89
90     private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
91
92     static {
93         TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
94         sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
95     }
96
97     public static void main(String[] args) throws IOException, SQLException, InterruptedException {
98         Properties p = new Properties();
99         try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
100             p.load(reader);
101         }
102         ServerConstants.init(p);
103         DatabaseConnection.init(p);
104
105         runSigner();
106     }
107
108     public static void stopSigner() throws InterruptedException {
109         Thread capturedRunner;
110         synchronized (SimpleSigner.class) {
111             if (runner == null) {
112                 throw new IllegalStateException("already stopped");
113             }
114             capturedRunner = runner;
115             running = false;
116             SimpleSigner.class.notifyAll();
117         }
118         capturedRunner.join();
119     }
120
121     public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
122         if (runner != null) {
123             throw new IllegalStateException("already running");
124         }
125         running = true;
126
127         runner = new Thread() {
128
129             @Override
130             public void run() {
131                 try (Link l = DatabaseConnection.newLink(false)) {
132                     readyCerts = new GigiPreparedStatement("SELECT certs.id AS id, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
133                             "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
134                             "INNER JOIN profiles ON profiles.id=certs.profile " + //
135                             "WHERE jobs.state='open' " + //
136                             "AND task='sign'");
137
138                     getSANSs = new GigiPreparedStatement("SELECT contents, type FROM `subjectAlternativeNames` " + //
139                             "WHERE `certId`=?");
140
141                     updateMail = new GigiPreparedStatement("UPDATE certs SET created=NOW(), serial=?, caid=?, expire=? WHERE id=?");
142                     warnMail = new GigiPreparedStatement("UPDATE jobs SET attempt=attempt+1, state=CASE WHEN attempt<3 THEN 'open'::`jobState` ELSE 'error'::`jobState` END WHERE id=?");
143
144                     revoke = new GigiPreparedStatement("SELECT certs.id, jobs.id FROM jobs INNER JOIN certs ON jobs.`targetId`=certs.id" + " WHERE jobs.state='open' AND task='revoke'");
145                     revokeCompleted = new GigiPreparedStatement("UPDATE `certs` SET revoked=NOW() WHERE id=?");
146
147                     finishJob = new GigiPreparedStatement("UPDATE jobs SET state='done' WHERE id=?");
148
149                     locateCA = new GigiPreparedStatement("SELECT id FROM cacerts WHERE keyname=?");
150
151                     work();
152                 } catch (InterruptedException e) {
153                     throw new Error(e);
154                 }
155             }
156
157         };
158         runner.start();
159     }
160
161     public static void ping() {
162         synchronized (SimpleSigner.class) {
163             SimpleSigner.class.notifyAll();
164             try {
165                 SimpleSigner.class.wait(2000);
166             } catch (InterruptedException e) {
167                 e.printStackTrace();
168             }
169         }
170     }
171
172     private synchronized static void work() {
173         try {
174             gencrl();
175         } catch (IOException e2) {
176             e2.printStackTrace();
177         } catch (InterruptedException e2) {
178             e2.printStackTrace();
179         }
180
181         while (running) {
182             try {
183                 signCertificates();
184                 revokeCertificates();
185
186                 SimpleSigner.class.notifyAll();
187                 SimpleSigner.class.wait(5000);
188             } catch (IOException e) {
189                 e.printStackTrace();
190             } catch (SQLException e) {
191                 e.printStackTrace();
192             } catch (InterruptedException e1) {
193             }
194         }
195         runner = null;
196     }
197
198     private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
199         GigiResultSet rs = revoke.executeQuery();
200         boolean worked = false;
201         while (rs.next()) {
202             int id = rs.getInt(1);
203             worked = true;
204             System.out.println("Revoke faked: " + id);
205             revokeCompleted.setInt(1, id);
206             revokeCompleted.executeUpdate();
207             finishJob.setInt(1, rs.getInt(2));
208             finishJob.executeUpdate();
209         }
210         if (worked) {
211             gencrl();
212         }
213     }
214
215     private static void gencrl() throws IOException, InterruptedException {
216         if (true) {
217             return;
218         }
219         String[] call = new String[] {
220                 "openssl",
221                 "ca",//
222                 "-cert",
223                 "../unassured.crt",//
224                 "-keyfile",
225                 "../unassured.key",//
226                 "-gencrl",//
227                 "-crlhours",//
228                 "12",//
229                 "-out",
230                 "../unassured.crl",//
231                 "-config",
232                 "../selfsign.config"
233
234         };
235         Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
236         if (p1.waitFor() != 0) {
237             System.out.println("Error while generating crl.");
238         }
239     }
240
241     private static void signCertificates() throws SQLException {
242         GigiResultSet rs = readyCerts.executeQuery();
243
244         Calendar c = Calendar.getInstance();
245         c.setTimeZone(TimeZone.getTimeZone("UTC"));
246         while (rs.next()) {
247             int id = rs.getInt("id");
248             System.out.println("sign: " + id);
249             try {
250                 Certificate crt = Certificate.getById(id);
251                 String csrType = rs.getString("csr_type");
252                 CSRType ct = CSRType.valueOf(csrType);
253
254                 Timestamp from = rs.getTimestamp("executeFrom");
255                 String length = rs.getString("executeTo");
256                 Date fromDate;
257                 Date toDate;
258                 if (from == null) {
259                     fromDate = new Date(System.currentTimeMillis());
260                 } else {
261                     fromDate = new Date(from.getTime());
262                 }
263                 if (length.endsWith("m") || length.endsWith("y")) {
264                     String num = length.substring(0, length.length() - 1);
265                     int inter = Integer.parseInt(num);
266                     c.setTime(fromDate);
267                     if (length.endsWith("m")) {
268                         c.add(Calendar.MONTH, inter);
269                     } else {
270                         c.add(Calendar.YEAR, inter);
271                     }
272                     toDate = c.getTime();
273                 } else {
274                     toDate = DateSelector.getDateFormat().parse(length);
275                 }
276
277                 getSANSs.setInt(1, id);
278                 GigiResultSet san = getSANSs.executeQuery();
279
280                 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
281                 while (san.next()) {
282                     altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
283                 }
284                 // TODO look them up!
285                 // cfg.println("keyUsage=critical," +
286                 // "digitalSignature, keyEncipherment, keyAgreement");
287                 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
288                 // cfg.close();
289
290                 int profile = rs.getInt("profile");
291                 CertificateProfile cp = CertificateProfile.getById(profile);
292                 String s = cp.getId() + "";
293                 while (s.length() < 4) {
294                     s = "0" + s;
295                 }
296                 s += "-" + cp.getKeyName() + ".cfg";
297                 Properties caP = new Properties();
298                 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
299                     caP.load(inStream);
300                 }
301
302                 HashMap<String, String> subj = new HashMap<>();
303                 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT name, value FROM `certAvas` WHERE `certId`=?")) {
304                     ps.setInt(1, rs.getInt("id"));
305                     GigiResultSet rs2 = ps.executeQuery();
306                     while (rs2.next()) {
307                         String name = rs2.getString("name");
308                         if (name.equals("EMAIL")) {
309                             name = "emailAddress";
310                         }
311                         subj.put(name, rs2.getString("value"));
312                     }
313                 }
314                 if (subj.size() == 0) {
315                     subj.put("CN", "<empty>");
316                     System.out.println("WARNING: DN was empty");
317                 }
318                 System.out.println(subj);
319
320                 PublicKey pk;
321                 byte[] data = crt.getAttachment(AttachmentType.CSR).getBytes("UTF-8");
322                 if (ct == CSRType.SPKAC) {
323                     String dt = new String(data, "UTF-8");
324                     if (dt.startsWith("SPKAC=")) {
325                         dt = dt.substring(6);
326                         data = dt.getBytes("UTF-8");
327                         System.out.println(dt);
328                     }
329                     SPKAC sp = new SPKAC(Base64.getDecoder().decode(data));
330                     pk = sp.getPubkey();
331                 } else {
332                     PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data, "UTF-8")));
333                     pk = p10.getSubjectPublicKeyInfo();
334                 }
335                 Calendar cal = GregorianCalendar.getInstance();
336                 String ca = caP.getProperty("ca") + "_" + cal.get(Calendar.YEAR) + (cal.get(Calendar.MONTH) >= 6 ? "_2" : "_1");
337                 File parent = new File("signer/ca");
338                 File[] caFiles = parent.listFiles();
339                 if (null == caFiles) {
340                     caFiles = new File[0];
341                 }
342                 if ( !new File(parent, ca).exists()) {
343                     System.out.println("CA " + ca + " not found. Searching for anything other remotely fitting.");
344                     for (File f : caFiles) {
345                         if (f.getName().startsWith(caP.getProperty("ca"))) {
346                             ca = f.getName();
347                             break;
348                         }
349                     }
350                 }
351                 File caKey = new File(parent, ca + "/ca.key");
352                 PrivateKey i = loadOpensslKey(caKey);
353
354                 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
355                 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
356                 StringBuilder b = new StringBuilder();
357                 b.append("-----BEGIN CERTIFICATE-----\r\n");
358                 b.append(Base64.getMimeEncoder().encodeToString(cert));
359                 b.append("-----END CERTIFICATE-----\r\n");
360                 crt.addAttachment(AttachmentType.CRT, b.toString());
361
362                 try (InputStream is = new ByteArrayInputStream(cert)) {
363                     locateCA.setString(1, ca);
364                     GigiResultSet caRs = locateCA.executeQuery();
365                     if ( !caRs.next()) {
366                         throw new Error("ca " + ca + " was not found");
367                     }
368
369                     CertificateFactory cf = CertificateFactory.getInstance("X.509");
370                     X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
371                     BigInteger serial = crtp.getSerialNumber();
372                     updateMail.setString(1, serial.toString(16));
373                     updateMail.setInt(2, caRs.getInt("id"));
374                     updateMail.setTimestamp(3, new Timestamp(toDate.getTime()));
375                     updateMail.setInt(4, id);
376                     updateMail.executeUpdate();
377
378                     finishJob.setInt(1, rs.getInt("jobid"));
379                     finishJob.executeUpdate();
380                     System.out.println("signed: " + id);
381                     continue;
382                 }
383
384             } catch (GeneralSecurityException e) {
385                 e.printStackTrace();
386             } catch (IOException e) {
387                 e.printStackTrace();
388             } catch (ParseException e) {
389                 e.printStackTrace();
390             } catch (GigiApiException e) {
391                 e.printStackTrace();
392             }
393             System.out.println("Error with: " + id);
394             warnMail.setInt(1, rs.getInt("jobid"));
395             warnMail.executeUpdate();
396
397         }
398         rs.close();
399     }
400
401     private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
402         byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
403         DerOutputStream dos = new DerOutputStream();
404         dos.putInteger(0);
405         new AlgorithmId(new ObjectIdentifier(new int[] {
406                 1, 2, 840, 113549, 1, 1, 1
407         })).encode(dos);
408         dos.putOctetString(p8b);
409         byte[] ctx = dos.toByteArray();
410         dos.reset();
411         dos.write(DerValue.tag_Sequence, ctx);
412         PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
413         PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
414         return i;
415     }
416
417     public static synchronized byte[] generateCert(PublicKey pk, PrivateKey prk, Map<String, String> subj, X500Principal issuer, List<SubjectAlternateName> altnames, Date fromDate, Date toDate, Digest digest, String eku) throws IOException, GeneralSecurityException {
418         File f = Paths.get("signer", "serial").toFile();
419         if ( !f.exists()) {
420             try (FileOutputStream fos = new FileOutputStream(f)) {
421                 fos.write("1".getBytes("UTF-8"));
422             }
423         }
424         try (FileInputStream fr = new FileInputStream(f)) {
425             byte[] serial = IOUtils.readURL(fr);
426             BigInteger ser = new BigInteger(new String(serial).trim());
427             ser = ser.add(BigInteger.ONE);
428
429             PrintWriter pw = new PrintWriter(f);
430             pw.println(ser);
431             pw.close();
432             if (digest != Digest.SHA256 && digest != Digest.SHA384 && digest != Digest.SHA512) {
433                 System.err.println("assuming sha256 either way ;-): " + digest);
434                 digest = Digest.SHA256;
435             }
436             ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
437                     1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : (digest == Digest.SHA384 ? 12 : 13)
438             });
439             AlgorithmId aid = new AlgorithmId(sha512withrsa);
440             Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : (digest == Digest.SHA384 ? "SHA384withRSA" : "SHA512withRSA"));
441
442             DerOutputStream cert = new DerOutputStream();
443             DerOutputStream content = new DerOutputStream();
444             {
445                 DerOutputStream version = new DerOutputStream();
446                 version.putInteger(2); // v3
447                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
448             }
449             content.putInteger(ser); // Serial
450             aid.encode(content);
451
452             {
453                 content.write(issuer.getEncoded());
454             }
455             {
456                 DerOutputStream notAround = new DerOutputStream();
457                 notAround.putUTCTime(fromDate);
458                 notAround.putUTCTime(toDate);
459                 content.write(DerValue.tag_Sequence, notAround);
460             }
461             {
462
463                 X500Name xn = genX500Name(subj);
464                 content.write(xn.getEncoded());
465             }
466             {
467                 content.write(pk.getEncoded());
468             }
469             {
470                 DerOutputStream extensions = new DerOutputStream();
471                 {
472                     addExtension(extensions, new ObjectIdentifier(new int[] {
473                             2, 5, 29, 17
474                     }), generateSAN(altnames));
475                     addExtension(extensions, new ObjectIdentifier(new int[] {
476                             2, 5, 29, 15
477                     }), generateKU());
478                     addExtension(extensions, new ObjectIdentifier(new int[] {
479                             2, 5, 29, 37
480                     }), generateEKU(eku));
481                     addExtension(extensions, new ObjectIdentifier(new int[] {
482                             1, 3, 6, 1, 5, 5, 7, 1, 1
483                     }), generateAIA());
484                 }
485                 DerOutputStream extensionsSeq = new DerOutputStream();
486                 extensionsSeq.write(DerValue.tag_Sequence, extensions);
487                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
488             }
489
490             DerOutputStream contentSeq = new DerOutputStream();
491
492             contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
493
494             s.initSign(prk);
495             s.update(contentSeq.toByteArray());
496
497             aid.encode(contentSeq);
498             contentSeq.putBitString(s.sign());
499             cert.write(DerValue.tag_Sequence, contentSeq);
500
501             // X509Certificate c = (X509Certificate)
502             // CertificateFactory.getInstance("X509").generateCertificate(new
503             // ByteArrayInputStream(cert.toByteArray()));
504             // c.verify(pk); only for self-signeds
505
506             byte[] res = cert.toByteArray();
507             cert.close();
508             return res;
509         }
510
511     }
512
513     private static byte[] generateAIA() throws IOException {
514         try (DerOutputStream dos = new DerOutputStream()) {
515             try (DerOutputStream seq = new DerOutputStream()) {
516                 seq.putOID(new ObjectIdentifier(new int[] {
517                         1, 3, 6, 1, 5, 5, 7, 48, 2
518                 }));
519                 seq.write((byte) 0x86, ("http://" + ServerConstants.getHostName(Host.OCSP_RESPONDER)).getBytes("UTF-8"));
520                 dos.write(DerValue.tag_Sequence, seq);
521             }
522             byte[] data = dos.toByteArray();
523             dos.reset();
524             dos.write(DerValue.tag_Sequence, data);
525             return dos.toByteArray();
526         }
527     }
528
529     private static byte[] generateKU() throws IOException {
530         try (DerOutputStream dos = new DerOutputStream()) {
531             dos.putBitString(new byte[] {
532                     (byte) 0b10101000
533             });
534             return dos.toByteArray();
535         }
536     }
537
538     private static byte[] generateEKU(String eku) throws IOException {
539
540         try (DerOutputStream dos = new DerOutputStream()) {
541             for (String name : eku.split(",")) {
542                 name = name.trim();
543                 ObjectIdentifier oid;
544                 switch (name) {
545                 case "serverAuth":
546                     oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
547                     break;
548                 case "clientAuth":
549                     oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
550                     break;
551                 case "codeSigning":
552                     oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
553                     break;
554                 case "emailProtection":
555                     oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
556                     break;
557                 case "OCSPSigning":
558                     oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.9");
559                     break;
560
561                 default:
562                     throw new Error(name);
563                 }
564                 dos.putOID(oid);
565             }
566             byte[] data = dos.toByteArray();
567             dos.reset();
568             dos.write(DerValue.tag_Sequence, data);
569             return dos.toByteArray();
570         }
571     }
572
573     public static X500Name genX500Name(Map<String, String> subj) throws IOException {
574         LinkedList<RDN> rdns = new LinkedList<>();
575         for (Entry<String, String> i : subj.entrySet()) {
576             RDN rdn = genRDN(i);
577             rdns.add(rdn);
578         }
579         return new X500Name(rdns.toArray(new RDN[rdns.size()]));
580     }
581
582     private static RDN genRDN(Entry<String, String> i) throws IOException {
583         DerOutputStream dos = new DerOutputStream();
584         dos.putUTF8String(i.getValue());
585         int[] oid;
586         String key = i.getKey();
587         switch (key) {
588         case "CN":
589             oid = new int[] {
590                     2, 5, 4, 3
591             };
592             break;
593         case "EMAIL":
594         case "emailAddress":
595             oid = new int[] {
596                     1, 2, 840, 113549, 1, 9, 1
597             };
598             break;
599         case "O":
600             oid = new int[] {
601                     2, 5, 4, 10
602             };
603             break;
604         case "OU":
605             oid = new int[] {
606                     2, 5, 4, 11
607             };
608             break;
609         case "ST":
610             oid = new int[] {
611                     2, 5, 4, 8
612             };
613             break;
614         case "L":
615             oid = new int[] {
616                     2, 5, 4, 7
617             };
618             break;
619         case "C":
620             oid = new int[] {
621                     2, 5, 4, 6
622             };
623             break;
624         default:
625             dos.close();
626             throw new Error("unknown RDN-type: " + key);
627         }
628         RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
629         dos.close();
630         return rdn;
631     }
632
633     private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
634         DerOutputStream SANs = new DerOutputStream();
635         SANs.putOID(oid);
636         SANs.putOctetString(extContent);
637
638         extensions.write(DerValue.tag_Sequence, SANs);
639     }
640
641     private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
642         DerOutputStream SANContent = new DerOutputStream();
643         for (SubjectAlternateName san : altnames) {
644             byte type = 0;
645             if (san.getType() == SANType.DNS) {
646                 type = (byte) GeneralNameInterface.NAME_DNS;
647             } else if (san.getType() == SANType.EMAIL) {
648                 type = (byte) GeneralNameInterface.NAME_RFC822;
649             } else {
650                 SANContent.close();
651                 throw new Error("" + san.getType());
652             }
653             SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes("UTF-8"));
654         }
655         DerOutputStream SANSeqContent = new DerOutputStream();
656         SANSeqContent.write(DerValue.tag_Sequence, SANContent);
657         byte[] byteArray = SANSeqContent.toByteArray();
658         SANContent.close();
659         SANSeqContent.close();
660         return byteArray;
661     }
662 }