1 package org.cacert.gigi.testUtils;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.ObjectInputStream;
8 import java.io.ObjectOutputStream;
9 import java.security.GeneralSecurityException;
10 import java.security.KeyPair;
11 import java.security.KeyPairGenerator;
12 import java.security.Signature;
13 import java.util.Properties;
14 import java.util.TimeZone;
16 import org.cacert.gigi.database.DatabaseConnection;
17 import org.cacert.gigi.util.PEM;
18 import org.junit.BeforeClass;
20 import sun.security.pkcs10.PKCS10;
21 import sun.security.pkcs10.PKCS10Attributes;
22 import sun.security.x509.X500Name;
25 * Base class for a Testsuite that makes use of the config variables that define
28 public abstract class ConfiguredTest {
30 static Properties testProps = new Properties();
32 public static Properties getTestProps() {
36 private static boolean envInited = false;
39 public static void initEnvironment() throws IOException {
40 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
45 try (FileInputStream inStream = new FileInputStream("config/test.properties")) {
46 testProps.load(inStream);
48 if ( !DatabaseConnection.isInited()) {
49 DatabaseConnection.init(testProps);
53 public static KeyPair generateKeypair() throws GeneralSecurityException {
54 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
56 KeyPair keyPair = null;
57 File f = new File("testKeypair");
59 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
60 keyPair = (KeyPair) ois.readObject();
61 } catch (ClassNotFoundException e) {
63 } catch (IOException e) {
67 keyPair = kpg.generateKeyPair();
68 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
69 oos.writeObject(keyPair);
71 } catch (IOException e) {
78 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
79 return generatePEMCSR(kp, dn, new PKCS10Attributes());
82 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
83 return generatePEMCSR(kp, dn, atts, "SHA256WithRSA");
86 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
87 PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
88 Signature s = Signature.getInstance(signature);
89 s.initSign(kp.getPrivate());
90 p10.encodeAndSign(new X500Name(dn), s);
91 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
96 public static String createUniqueName() {
97 return "test" + System.currentTimeMillis() + "a" + (count++) + "u";