1 package org.cacert.gigi;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.security.GeneralSecurityException;
9 import java.security.cert.CertificateFactory;
10 import java.security.cert.X509Certificate;
12 import java.sql.PreparedStatement;
13 import java.sql.ResultSet;
14 import java.sql.SQLException;
15 import java.util.Arrays;
16 import java.util.Collections;
17 import java.util.LinkedList;
18 import java.util.List;
20 import org.cacert.gigi.database.DatabaseConnection;
21 import org.cacert.gigi.util.Job;
22 import org.cacert.gigi.util.KeyStorage;
23 import org.cacert.gigi.util.Notary;
25 public class Certificate {
28 EMAIL("email"), DNS("DNS");
30 private final String opensslName;
32 private SANType(String opensslName) {
33 this.opensslName = opensslName;
36 public String getOpensslName() {
41 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
47 public SubjectAlternateName(SANType type, String name) {
52 public String getName() {
56 public SANType getType() {
61 public int compareTo(SubjectAlternateName o) {
62 int i = type.compareTo(o.type);
66 return name.compareTo(o.name);
70 public int hashCode() {
73 result = prime * result + ((name == null) ? 0 : name.hashCode());
74 result = prime * result + ((type == null) ? 0 : type.hashCode());
79 public boolean equals(Object obj) {
86 if (getClass() != obj.getClass()) {
89 SubjectAlternateName other = (SubjectAlternateName) obj;
91 if (other.name != null) {
94 } else if ( !name.equals(other.name)) {
97 if (type != other.type) {
105 public enum CSRType {
113 private String serial;
119 private String csrName;
121 private String crtName;
123 private String csr = null;
125 private CSRType csrType;
127 private List<SubjectAlternateName> sans;
129 private CertificateProfile profile;
131 public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) {
132 this.ownerId = ownerId;
136 this.csrType = csrType;
137 this.profile = profile;
138 this.sans = Arrays.asList(sans);
141 private Certificate(String serial) {
143 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid, profile FROM `certs` WHERE serial=?");
144 ps.setString(1, serial);
145 ResultSet rs = ps.executeQuery();
147 throw new IllegalArgumentException("Invalid mid " + serial);
149 this.id = rs.getInt(1);
150 dn = rs.getString(2);
151 md = rs.getString(3);
152 csrName = rs.getString(4);
153 crtName = rs.getString(5);
154 ownerId = rs.getInt(6);
155 profile = CertificateProfile.getById(rs.getInt(7));
156 this.serial = serial;
158 PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM `subjectAlternativeNames` WHERE certId=?");
160 ResultSet rs2 = ps2.executeQuery();
161 sans = new LinkedList<>();
163 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
168 } catch (SQLException e) {
173 public enum CertificateStatus {
175 * This certificate is not in the database, has no id and only exists as
180 * The certificate has been signed. It is stored in the database.
181 * {@link Certificate#cert()} is valid.
186 * The certificate has been revoked.
191 * If this certificate cannot be updated because an error happened in
196 private CertificateStatus() {}
200 public CertificateStatus getStatus() throws SQLException {
202 return CertificateStatus.DRAFT;
204 PreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial FROM certs WHERE id=?");
205 searcher.setInt(1, id);
206 ResultSet rs = searcher.executeQuery();
208 throw new IllegalStateException("Certificate not in Database");
211 crtName = rs.getString(1);
212 serial = rs.getString(4);
213 if (rs.getTime(2) == null) {
214 return CertificateStatus.DRAFT;
216 if (rs.getTime(2) != null && rs.getTime(3) == null) {
217 return CertificateStatus.ISSUED;
219 return CertificateStatus.REVOKED;
224 * the date from which on the certificate should be valid. (or
225 * null if it should be valid instantly)
227 * the period for which the date should be valid. (a
228 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
230 * @return A job which can be used to monitor the progress of this task.
231 * @throws IOException
232 * for problems with writing the CSR/SPKAC
233 * @throws SQLException
234 * for problems with writing to the DB
235 * @throws GigiApiException
236 * if the period is bogus
238 public Job issue(Date start, String period) throws IOException, SQLException, GigiApiException {
239 if (getStatus() != CertificateStatus.DRAFT) {
240 throw new IllegalStateException();
242 Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0);
244 PreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?, subject=?, csr_type=?, crt_name='', memid=?, profile=?");
245 inserter.setString(1, md);
246 inserter.setString(2, dn);
247 inserter.setString(3, csrType.toString());
248 inserter.setInt(4, ownerId);
249 inserter.setInt(5, profile.getId());
251 id = DatabaseConnection.lastInsertId(inserter);
252 File csrFile = KeyStorage.locateCsr(id);
253 csrName = csrFile.getPath();
254 FileOutputStream fos = new FileOutputStream(csrFile);
255 fos.write(csr.getBytes());
258 // TODO draft to insert SANs
259 PreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO subjectAlternativeNames SET certId=?, contents=?, type=?");
260 for (SubjectAlternateName subjectAlternateName : sans) {
262 san.setString(2, subjectAlternateName.getName());
263 san.setString(3, subjectAlternateName.getType().getOpensslName());
267 PreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE certs SET csr_name=? WHERE id=?");
268 updater.setString(1, csrName);
269 updater.setInt(2, id);
271 return Job.sign(this, start, period);
275 public Job revoke() throws SQLException {
276 if (getStatus() != CertificateStatus.ISSUED) {
277 throw new IllegalStateException();
279 return Job.revoke(this);
283 public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
284 CertificateStatus status = getStatus();
285 if (status != CertificateStatus.ISSUED) {
286 throw new IllegalStateException(status + " is not wanted here.");
288 InputStream is = null;
289 X509Certificate crt = null;
291 is = new FileInputStream(crtName);
292 CertificateFactory cf = CertificateFactory.getInstance("X.509");
293 crt = (X509Certificate) cf.generateCertificate(is);
302 public Certificate renew() {
310 public String getSerial() {
313 } catch (SQLException e) {
319 public String getDistinguishedName() {
323 public String getMessageDigest() {
327 public int getOwnerId() {
331 public List<SubjectAlternateName> getSANs() {
332 return Collections.unmodifiableList(sans);
335 public CertificateProfile getProfile() {
339 public static Certificate getBySerial(String serial) {
342 return new Certificate(serial);
343 } catch (IllegalArgumentException e) {