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;
15 import java.util.regex.Matcher;
16 import java.util.regex.Pattern;
18 import org.cacert.gigi.database.DatabaseConnection;
19 import org.cacert.gigi.util.PEM;
20 import org.junit.BeforeClass;
22 import sun.security.pkcs10.PKCS10;
23 import sun.security.pkcs10.PKCS10Attributes;
24 import sun.security.x509.X500Name;
27 * Base class for a Testsuite that makes use of the config variables that define
30 public abstract class ConfiguredTest {
32 static Properties testProps = new Properties();
34 public static Properties getTestProps() {
38 private static boolean envInited = false;
41 public static void initEnvironment() throws IOException {
42 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
47 try (FileInputStream inStream = new FileInputStream("config/test.properties")) {
48 testProps.load(inStream);
50 if ( !DatabaseConnection.isInited()) {
51 DatabaseConnection.init(testProps);
55 public static KeyPair generateKeypair() throws GeneralSecurityException {
56 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
58 KeyPair keyPair = null;
59 File f = new File("testKeypair");
61 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
62 keyPair = (KeyPair) ois.readObject();
63 } catch (ClassNotFoundException e) {
65 } catch (IOException e) {
69 keyPair = kpg.generateKeyPair();
70 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
71 oos.writeObject(keyPair);
73 } catch (IOException e) {
80 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
81 return generatePEMCSR(kp, dn, new PKCS10Attributes());
84 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
85 return generatePEMCSR(kp, dn, atts, "SHA256WithRSA");
88 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
89 PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
90 Signature s = Signature.getInstance(signature);
91 s.initSign(kp.getPrivate());
92 p10.encodeAndSign(new X500Name(dn), s);
93 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
98 public static String createUniqueName() {
99 return "test" + System.currentTimeMillis() + "a" + (count++) + "u";
102 public static int countRegex(String text, String pattern) {
103 Pattern p = Pattern.compile(pattern);
104 Matcher m = p.matcher(text);