Example #1
0
  private X509Certificate createAll(int index) throws GeneralSecurityException, IOException {
    logger.info("Generating CA key pair");
    KeyPair ca = CertUtil.generateKeyPair(CA_CERT_ALGORITHM, CA_CERT_BITS);
    OpenSSLKey caKey = new BouncyCastleOpenSSLKey(ca.getPrivate());
    logger.info("Self-signing CA certificate");
    X509Certificate caCert = genCert(ca.getPrivate(), ca.getPublic(), CA_CERT_DN, CA_CERT_DN, null);

    logger.info("Generating user key pair");
    KeyPair user = CertUtil.generateKeyPair(CA_CERT_ALGORITHM, CA_CERT_BITS);
    OpenSSLKey userKey = new BouncyCastleOpenSSLKey(user.getPrivate());
    logger.info("Signing user certificate");
    X509Certificate userCert =
        genCert(
            ca.getPrivate(),
            user.getPublic(),
            USER_CERT_DN,
            CA_CERT_DN,
            createExtensions(ca.getPublic(), user.getPublic()));
    logger.info("Generating proxy certificate");
    GlobusCredential proxy = makeProxy(user, userCert);

    try {
      logger.info("Writing keys, certificates, and proxy");
      writeKey(caKey, makeFile(CA_KEY_NAME_PREFIX, index));
      writeCert(caCert, makeFile(CA_CRT_NAME_PREFIX, index));
      writeKey(userKey, makeFile(USER_KEY_NAME_PREFIX, index));
      writeCert(userCert, makeFile(USER_CRT_NAME_PREFIX, index));
      writeProxy(proxy, makeFile(PROXY_NAME_PREFIX, index));
      copySigningPolicy(index);
    } catch (GeneralSecurityException e) {
      deleteAll(index);
      throw e;
    }
    return cert;
  }
Example #2
0
  private static X509Certificate getSelfCertificate(
      String myname, long validity, String sigAlg, KeyPair keyPair, String provider)
      throws OperatorCreationException, CertificateException {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);

    // Add all mandatory attributes
    if (LOG.isDebugEnabled()) {
      LOG.debug("keystore signing algorithm " + sigAlg);
    }

    final PublicKey publicKey = keyPair.getPublic();
    if (publicKey == null) {
      throw new IllegalArgumentException("Public key is null");
    }

    X509v3CertificateBuilder cg =
        new JcaX509v3CertificateBuilder(
            new X500Principal(myname),
            BigInteger.valueOf(firstDate.getTime()),
            firstDate,
            lastDate,
            new X500Principal(myname),
            publicKey);
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(sigAlg);
    contentSignerBuilder.setProvider(provider);

    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());

    return new JcaX509CertificateConverter().getCertificate(cg.build(contentSigner));
  }
Example #3
0
  public static X509Certificate makeCertificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN, boolean _ca)
      throws GeneralSecurityException, IOException, OperatorCreationException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509v3CertificateBuilder v3CertGen =
        new JcaX509v3CertificateBuilder(
            new X500Name(_issDN),
            allocateSerialNumber(),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
            new X500Name(_subDN),
            subPub);

    JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub);

    v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(subPub));

    v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issPub));

    v3CertGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(_ca));

    X509Certificate _cert =
        new JcaX509CertificateConverter()
            .setProvider("SC")
            .getCertificate(v3CertGen.build(contentSignerBuilder.build(issPriv)));

    _cert.checkValidity(new Date());
    _cert.verify(issPub);

    return _cert;
  }
  private static X509Certificate makeCertificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
      throws GeneralSecurityException, IOException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    v3CertGen.reset();
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(new X509Name(_issDN));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)));
    v3CertGen.setSubjectDN(new X509Name(_subDN));
    v3CertGen.setPublicKey(subPub);

    v3CertGen.setSignatureAlgorithm("SHA1WithRSA");

    X509Certificate _cert = v3CertGen.generate(issPriv, "SunRsaSign");

    _cert.checkValidity(new Date());
    _cert.verify(issPub);

    return _cert;
  }
  /** Generate a X500PrivateCredential for the root entity. */
  public static X500PrivateCredential createRootCredential() throws Exception {
    KeyPair rootPair = generateRSAKeyPair();
    X509Certificate rootCert = generateRootCert(rootPair);

    return new X500PrivateCredential(
        rootCert, rootPair.getPrivate(), ConfigurationClass.ROOT_ALIAS);
  }
Example #6
0
  @Test
  public void testBadAttributes() throws Exception {
    DKIMSignature signed = new DKIMSignature();
    signed.setAttribute("path", "/hello/world");
    signed.setTimestamp();
    signed.addHeader("Visa");
    signed.addHeader("Visa");
    MultivaluedMapImpl<String, String> headers = new MultivaluedMapImpl<String, String>();
    headers.add("Visa", "v1");
    headers.add("Visa", "v2");
    headers.add("Visa", "v3");
    signed.sign(headers, null, keys.getPrivate());

    String signedHeader = signed.toString();

    System.out.println(signedHeader);

    DKIMSignature verified = new DKIMSignature(signedHeader);

    HashMap<String, String> requiredAttributes = new HashMap<String, String>();
    requiredAttributes.put("path", "/hello/world");

    Verification verification = new Verification();
    verification.getRequiredAttributes().put("path", "/hello");

    MultivaluedMap<String, String> verifiedHeaders = null;
    try {
      verifiedHeaders = verification.verify(verified, headers, null, keys.getPublic());
      Assert.fail("should fail");
    } catch (SignatureException e) {
    }
  }
Example #7
0
  private static X509CertificateHolder makeV3Certificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
      throws GeneralSecurityException, IOException, OperatorCreationException, CertException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509v3CertificateBuilder v1CertGen =
        new JcaX509v3CertificateBuilder(
            new X500Name(_issDN),
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
            new X500Name(_subDN),
            subPub);

    ContentSigner signer =
        new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(issPriv);

    X509CertificateHolder certHolder = v1CertGen.build(signer);

    ContentVerifierProvider verifier =
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(issPub);

    assertTrue(certHolder.isSignatureValid(verifier));

    return certHolder;
  }
  @Before
  public void setUp() throws Exception {
    this.servletTester = new ServletTester();
    String pathSpec = "/test.ocsp";
    this.servletTester.addServlet(OcspResponderTestServlet.class, pathSpec);
    this.servletTester.start();

    String servletUrl = this.servletTester.createSocketConnector(true);
    this.ocspUri = new URI(servletUrl + pathSpec);

    this.testedInstance = new OnlineOcspRepository();

    OcspResponderTestServlet.reset();

    this.rootKeyPair = TrustTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    this.rootCertificate =
        TrustTestUtils.generateSelfSignedCertificate(
            this.rootKeyPair, "CN=TestRoot", notBefore, notAfter);

    KeyPair keyPair = TrustTestUtils.generateKeyPair();
    this.certificate =
        TrustTestUtils.generateCertificate(
            keyPair.getPublic(),
            "CN=Test",
            notBefore,
            notAfter,
            this.rootCertificate,
            this.rootKeyPair.getPrivate());

    // required for org.bouncycastle.ocsp.CertificateID
    Security.addProvider(new BouncyCastleProvider());
  }
Example #9
0
 /**
  * Sets the public parameters to the ones given in string parameter
  *
  * @param params must be of the form g p l, where g, p, and l are the public parameters for DH key
  *     exchange
  */
 public void setPubParams(String params) {
   String[] parts = params.split(" ");
   BigInteger g = new BigInteger(parts[0]);
   BigInteger p = new BigInteger(parts[1]);
   int l = Integer.parseInt(parts[2]);
   KeyPair keyPair = getKeyPair(g, p, l);
   this.pubKey = keyPair.getPublic();
   this.privKey = keyPair.getPrivate();
   ByteArrayOutputStream baos = null;
   ObjectOutputStream oos = null;
   try {
     baos = new ByteArrayOutputStream();
     oos = new ObjectOutputStream(baos);
     oos.writeObject(pubKey);
     byte[] pubKeyBytes = baos.toByteArray();
     this.strPubKey = new Base64().encodeToString(pubKeyBytes);
     oos.close();
     baos.close();
   } catch (Exception e) {
     if (DEBUG) {
       System.out.println("Not persisted");
       e.printStackTrace();
     }
   }
 }
Example #10
0
  public void init(int key_size) throws Exception {
    String name = null;
    if (key_size == 256) name = "secp256r1";
    else if (key_size == 384) name = "secp384r1";
    else if (key_size == 521) name = "secp521r1";
    else throw new JSchException("unsupported key size: " + key_size);

    for (int i = 0; i < 1000; i++) {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
      ECGenParameterSpec ecsp = new ECGenParameterSpec(name);
      kpg.initialize(ecsp);
      KeyPair kp = kpg.genKeyPair();
      prvKey = (ECPrivateKey) kp.getPrivate();
      pubKey = (ECPublicKey) kp.getPublic();
      params = pubKey.getParams();
      d = ((ECPrivateKey) prvKey).getS().toByteArray();
      ECPoint w = pubKey.getW();
      r = w.getAffineX().toByteArray();
      s = w.getAffineY().toByteArray();

      if (r.length != s.length) continue;
      if (key_size == 256 && r.length == 32) break;
      if (key_size == 384 && r.length == 48) break;
      if (key_size == 521 && r.length == 66) break;
    }
    if (d.length < r.length) {
      d = insert0(d);
    }
  }
Example #11
0
  public static void main(String[] args) throws NoSuchAlgorithmException {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    KeyPair par = keyGen.generateKeyPair();
    prk = par.getPrivate();
    pbk = par.getPublic();

    Registry reg = null;
    System.out.println("Creando conexion remota");
    try {
      reg = LocateRegistry.createRegistry(5555);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("Creando objeto servidor");
    Servidor s = new Servidor();
    try {
      reg.rebind("Operaciones", (InterfaceRemota) UnicastRemoteObject.exportObject(s, 0));
    } catch (Exception e) {
      e.printStackTrace();
    }
    while (true) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ex) {
        Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
  public void main(Provider p) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
    kpg.initialize(512);
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey privateKey = kp.getPrivate();
    PublicKey publicKey = kp.getPublic();
    Signature sig = Signature.getInstance("MD5withRSA", p);
    byte[] data = new byte[10 * 1024];
    new Random().nextBytes(data);
    sig.initSign(privateKey);
    sig.initSign(privateKey);
    sig.update(data);
    sig.initSign(privateKey);
    sig.update(data);
    byte[] signature = sig.sign();
    sig.update(data);
    sig.initSign(privateKey);
    sig.update(data);
    sig.sign();
    sig.sign();
    sig.initSign(privateKey);
    sig.sign();

    System.out.println("All tests passed");
  }
  public static void main(String[] args) throws Exception {
    byte[] input = new byte[] {(byte) 0xbe, (byte) 0xef};
    Cipher cipher = Cipher.getInstance("ElGamal/None/NoPadding", "BC");

    SecureRandom random = Utils.createFixedRandom();

    // create the keys
    KeyPairGenerator generator = KeyPairGenerator.getInstance("ElGamal", "BC");

    generator.initialize(256, random);

    KeyPair pair = generator.generateKeyPair();
    Key pubKey = pair.getPublic();
    Key privKey = pair.getPrivate();

    System.out.println("input : " + Utils.toHex(input));

    // encryption step

    cipher.init(Cipher.ENCRYPT_MODE, pubKey, random);

    byte[] cipherText = cipher.doFinal(input);

    System.out.println("cipher: " + Utils.toHex(cipherText));

    // decryption step

    cipher.init(Cipher.DECRYPT_MODE, privKey);

    byte[] plainText = cipher.doFinal(cipherText);

    System.out.println("plain : " + Utils.toHex(plainText));
  }
  @Test
  public void shouldRoundTripBuildParseRpkiCaCertRequest()
      throws RpkiCaCertificateRequestParserException {

    RpkiCaCertificateRequestBuilder requestBuilder = new RpkiCaCertificateRequestBuilder();

    URI caRepositoryUri = URI.create("rsync://host/module/subdir/");
    URI manifestUri = URI.create("rsync://host/module/subdir/subject.mft");
    X500Principal subject = new X500Principal("CN=subject");
    KeyPair keyPair = PregeneratedKeyPairFactory.getInstance().generate();

    requestBuilder.withCaRepositoryUri(caRepositoryUri);
    requestBuilder.withManifestUri(manifestUri);
    requestBuilder.withSubject(subject);
    PKCS10CertificationRequest pkcs10Request = requestBuilder.build(keyPair);

    assertNotNull(pkcs10Request);

    RpkiCaCertificateRequestParser requestParser =
        new RpkiCaCertificateRequestParser(pkcs10Request);

    assertEquals(caRepositoryUri, requestParser.getCaRepositoryUri());
    assertEquals(manifestUri, requestParser.getManifestUri());
    assertEquals(keyPair.getPublic(), requestParser.getPublicKey());
  }
  /**
   * Generate version 1 self signed {@link java.security.cert.X509Certificate}..
   *
   * @param caKeyPair the CA key pair
   * @param subject the subject name
   * @return the x509 certificate
   * @throws Exception the exception
   */
  public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject)
      throws Exception {

    try {
      X500Name subjectDN = new X500Name("CN=" + subject);
      BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
      Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.YEAR, 10);
      Date validityEndDate = new Date(calendar.getTime().getTime());
      SubjectPublicKeyInfo subPubKeyInfo =
          SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded());

      X509v1CertificateBuilder builder =
          new X509v1CertificateBuilder(
              subjectDN,
              serialNumber,
              validityStartDate,
              validityEndDate,
              subjectDN,
              subPubKeyInfo);
      X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));

      return new JcaX509CertificateConverter().getCertificate(holder);
    } catch (Exception e) {
      throw new RuntimeException("Error creating X509v1Certificate.", e);
    }
  }
 /** This method generates public and private keys. */
 public static void generateKey() throws Exception {
   KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA);
   gen.initialize(512, new SecureRandom());
   KeyPair keyPair = gen.generateKeyPair();
   pubKey = keyPair.getPublic();
   priKey = keyPair.getPrivate();
 }
Example #17
0
  @Test
  public void testAttributes() throws Exception {
    DKIMSignature signed = new DKIMSignature();
    signed.setAttribute("path", "/hello/world");
    signed.setTimestamp();
    signed.addHeader("Visa");
    signed.addHeader("Visa");
    MultivaluedMapImpl<String, String> headers = new MultivaluedMapImpl<String, String>();
    headers.add("Visa", "v1");
    headers.add("Visa", "v2");
    headers.add("Visa", "v3");
    signed.sign(headers, null, keys.getPrivate());

    String signedHeader = signed.toString();

    System.out.println(signedHeader);

    DKIMSignature verified = new DKIMSignature(signedHeader);

    HashMap<String, String> requiredAttributes = new HashMap<String, String>();
    requiredAttributes.put("path", "/hello/world");

    Verification verification = new Verification();
    verification.getRequiredAttributes().put("path", "/hello/world");

    MultivaluedMap<String, String> verifiedHeaders =
        verification.verify(verified, headers, null, keys.getPublic());
    Assert.assertEquals(verifiedHeaders.size(), 1);
    List<String> visas = verifiedHeaders.get("Visa");
    Assert.assertNotNull(visas);
    Assert.assertEquals(visas.size(), 2);
    System.out.println(visas);
    Assert.assertEquals(visas.get(0), "v3");
    Assert.assertEquals(visas.get(1), "v2");
  }
  private static String csr() {
    try {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      keyGen.initialize(2048);
      KeyPair keyPair = keyGen.generateKeyPair();
      X500Principal subject =
          new X500Principal(
              "CN = edea87b4-034d-48dc-94dd-e7cdcfdde370/10562468, OU = fgdfgretertgdfg, O = VW, L = US");
      ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate());
      PKCS10CertificationRequestBuilder builder =
          new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic());
      PKCS10CertificationRequest csr = builder.build(signer);

      String type = "CERTIFICATE REQUEST";
      PemObject pem = new PemObject(type, csr.getEncoded());
      StringWriter str = new StringWriter();
      PEMWriter pemWriter = new PEMWriter(str);
      pemWriter.writeObject(pem);
      pemWriter.close();
      str.close();
      Log.d("Test", "" + str);
      return Base64Util.getStringAsBase64(str.toString());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (OperatorCreationException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }
Example #19
0
  @Test
  public void testCMD() throws Exception {
    Authentication auth =
        new SkeletonKeyClientBuilder()
            .username("wburke")
            .password("geheim")
            .authentication("Skeleton Key");
    ResteasyClient client = new ResteasyClient();
    WebTarget target = client.target(generateBaseUrl());
    String tiny = target.path("tokens").path("url").request().post(Entity.json(auth), String.class);
    System.out.println(tiny);
    System.out.println("tiny.size: " + tiny.length());
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    X509Certificate cert = KeyTools.generateTestCertificate(keyPair);

    byte[] signed = p7s(privateKey, cert, null, tiny.getBytes());

    CMSSignedData data = new CMSSignedData(signed);
    byte[] bytes = (byte[]) data.getSignedContent().getContent();
    System.out.println("BYTES: " + new String(bytes));
    System.out.println("size:" + signed.length);
    System.out.println("Base64.size: " + Base64.encodeBytes(signed).length());

    SignerInformation signer =
        (SignerInformation) data.getSignerInfos().getSigners().iterator().next();
    System.out.println("valid: " + signer.verify(cert, "BC"));
  }
Example #20
0
  public static Map<String, Object> createSslConfig(
      boolean useClientCert, boolean trustStore, Mode mode, File trustStoreFile, String certAlias)
      throws IOException, GeneralSecurityException {
    Map<String, X509Certificate> certs = new HashMap<String, X509Certificate>();
    File keyStoreFile;
    Password password;

    if (mode == Mode.SERVER) password = new Password("ServerPassword");
    else password = new Password("ClientPassword");

    Password trustStorePassword = new Password("TrustStorePassword");

    if (useClientCert) {
      keyStoreFile = File.createTempFile("clientKS", ".jks");
      KeyPair cKP = generateKeyPair("RSA");
      X509Certificate cCert = generateCertificate("CN=localhost, O=client", cKP, 30, "SHA1withRSA");
      createKeyStore(keyStoreFile.getPath(), password, "client", cKP.getPrivate(), cCert);
      certs.put(certAlias, cCert);
    } else {
      keyStoreFile = File.createTempFile("serverKS", ".jks");
      KeyPair sKP = generateKeyPair("RSA");
      X509Certificate sCert = generateCertificate("CN=localhost, O=server", sKP, 30, "SHA1withRSA");
      createKeyStore(keyStoreFile.getPath(), password, password, "server", sKP.getPrivate(), sCert);
      certs.put(certAlias, sCert);
    }

    if (trustStore) {
      createTrustStore(trustStoreFile.getPath(), trustStorePassword, certs);
    }

    Map<String, Object> sslConfig =
        createSslConfig(mode, keyStoreFile, password, password, trustStoreFile, trustStorePassword);
    return sslConfig;
  }
Example #21
0
  public void testProtectedMessage() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);

    kGen.initialize(512);

    KeyPair kp = kGen.generateKeyPair();
    X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test");

    GeneralName sender = new GeneralName(new X500Name("CN=Sender"));
    GeneralName recipient = new GeneralName(new X500Name("CN=Recip"));

    ContentSigner signer =
        new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(kp.getPrivate());
    ProtectedPKIMessage message =
        new ProtectedPKIMessageBuilder(sender, recipient)
            .setBody(
                new PKIBody(
                    PKIBody.TYPE_INIT_REP,
                    CertRepMessage.getInstance(new DERSequence(new DERSequence()))))
            .addCMPCertificate(cert)
            .build(signer);

    X509Certificate jcaCert =
        new JcaX509CertificateConverter()
            .setProvider(BC)
            .getCertificate(message.getCertificates()[0]);
    ContentVerifierProvider verifierProvider =
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(jcaCert.getPublicKey());

    assertTrue(message.verify(verifierProvider));

    assertEquals(sender, message.getHeader().getSender());
    assertEquals(recipient, message.getHeader().getRecipient());
  }
Example #22
0
  /**
   * Create a self-signed X.509 Certificate. From
   * http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
   *
   * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
   * @param pair the KeyPair
   * @param days how many days from now the Certificate is valid for
   * @param algorithm the signing algorithm, eg "SHA1withRSA"
   * @return the self-signed certificate
   * @throws CertificateException thrown if a security error or an IO error ocurred.
   */
  public static X509Certificate generateCertificate(
      String dn, KeyPair pair, int days, String algorithm) throws CertificateException {

    try {
      Security.addProvider(new BouncyCastleProvider());
      AlgorithmIdentifier sigAlgId =
          new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
      AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
      AsymmetricKeyParameter privateKeyAsymKeyParam =
          PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
      SubjectPublicKeyInfo subPubKeyInfo =
          SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
      ContentSigner sigGen =
          new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
      X500Name name = new X500Name(dn);
      Date from = new Date();
      Date to = new Date(from.getTime() + days * 86400000L);
      BigInteger sn = new BigInteger(64, new SecureRandom());

      X509v1CertificateBuilder v1CertGen =
          new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
      X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
      return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
      throw ce;
    } catch (Exception e) {
      throw new CertificateException(e);
    }
  }
Example #23
0
 private static Key loadKeyEncryptionKey() throws Exception {
   Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
   PEMReader pr = new PEMReader(new FileReader(EncryptTool.PRIVATE_KEY));
   KeyPair k = (KeyPair) pr.readObject();
   pr.close();
   return k.getPrivate();
 }
  @Test
  public void testGenerateRSA() {
    /*
     * Init Provider
     */
    ProviderManagement providerManagement = new ProviderManagement();
    providerManagement.initProvider("BC");
    /*
     * Generate Key RSA 1024-bit
     * return KeyPair
     */
    int lengthKeyRSA = 1024;
    String cryptoProvider = "BC";

    KeyManagementRSA keyManagementRSA = new KeyManagementRSA();
    KeyPair keyPair = keyManagementRSA.generateRSA(lengthKeyRSA, cryptoProvider);

    /*
     * Get Modulus & Exponent Public Key
     */
    RSAPublicKey rsaPubKey = (RSAPublicKey) keyPair.getPublic();

    /*
     * Test Result
     */
    assertEquals(lengthKeyRSA, rsaPubKey.getModulus().bitLength());
  }
  public void testSelfSignedCert() throws Exception {
    KeyPair keyPair = createKeyPair(1024, "secret");

    // Certificate
    String email = "*****@*****.**";
    String domain = "tigase.org";
    String ou = "XMPP Service";
    String o = "Tigase.org";
    String l = "Cambourne";
    String st = "Cambridgeshire";
    String c = "UK";

    // System.out.println("Creating self-signed certificate for issuer: " + domain);

    X509Certificate cert = createSelfSignedCertificate(email, domain, ou, o, l, st, c, keyPair);

    cert.checkValidity();
    assertTrue("Checked certificate validty for today - valid", true);

    try {
      cert.checkValidity(new Date(System.currentTimeMillis() - (1000 * 3600 * 24)));
      fail("Checked certificate validty for yesterday - valid");
    } catch (CertificateNotYetValidException e) {
      assertTrue("Checked certificate validty for yesterday - not valid", true);
    }

    cert.verify(keyPair.getPublic());
    assertTrue("Verified certificate with public key - done", true);
  }
  @Test
  public void testKeygenToFileOutputStream()
      throws NoSuchAlgorithmException, NoSuchProviderException, IOException {
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();

    final PrivateKey priv = pair.getPrivate();
    final PublicKey pub = pair.getPublic();

    // Write the private key to a file
    FileOutputStream privOS = new FileOutputStream("RSAPrivateKey.key");
    Assert.assertNotNull(privOS);
    privOS.write(priv.getEncoded());
    privOS.close();

    // Write the private key to a file
    FileOutputStream publicOS = new FileOutputStream("RSAPublicKey.key");
    Assert.assertNotNull(publicOS);
    publicOS.write(pub.getEncoded());
    publicOS.close();
  }
Example #27
0
  public static X509Certificate makeV1Certificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
      throws GeneralSecurityException, IOException, OperatorCreationException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509v1CertificateBuilder v1CertGen =
        new JcaX509v1CertificateBuilder(
            new X500Name(_issDN),
            allocateSerialNumber(),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
            new X500Name(_subDN),
            subPub);

    JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub);

    X509Certificate _cert =
        new JcaX509CertificateConverter()
            .setProvider("SC")
            .getCertificate(v1CertGen.build(contentSignerBuilder.build(issPriv)));

    _cert.checkValidity(new Date());
    _cert.verify(issPub);

    return _cert;
  }
Example #28
0
  public static ECPublicKey PrivateKeytoECPublicKey(byte[] privateKey)
      throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException {
    KeyPairGenerator kpg = null;
    kpg = KeyPairGenerator.getInstance("EC");

    ECGenParameterSpec gps = new ECGenParameterSpec("secp256k1"); // NIST P-256
    kpg.initialize(gps);
    KeyPair apair = kpg.generateKeyPair();
    ECPublicKey apub = (ECPublicKey) apair.getPublic();
    ECParameterSpec aspec = apub.getParams();

    byte[] publicKeyb = Address.privateKeyToPublicKey(Utils.toHex(privateKey), false);

    byte[] publicKeybx = new byte[32];
    byte[] publicKeyby = new byte[32];
    System.arraycopy(publicKeyb, 1, publicKeybx, 0, 32);
    System.arraycopy(publicKeyb, 33, publicKeyby, 0, 32);
    BigInteger x = new BigInteger(1, publicKeybx);
    BigInteger y = new BigInteger(1, publicKeyby);

    java.security.spec.ECPoint cpoint = new java.security.spec.ECPoint(x, y);
    ECPublicKeySpec cpubs = new ECPublicKeySpec(cpoint, aspec);
    ECPublicKey cpub = null;
    KeyFactory kfa = null;
    kfa = KeyFactory.getInstance("EC");
    return cpub = (ECPublicKey) kfa.generatePublic(cpubs);
  }
  public static PKCS10CertificationRequest genPKCS10(KeyPair kp) throws Exception {
    String sigName = "SHA1withRSA";

    X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE);
    x500NameBld.addRDN(BCStyle.C, "AU");
    x500NameBld.addRDN(BCStyle.ST, "Victoria");
    x500NameBld.addRDN(BCStyle.L, "Melbourne");
    x500NameBld.addRDN(BCStyle.O, "The Legion of the Bouncy Castle");
    X500Name subject = x500NameBld.build();

    PKCS10CertificationRequestBuilder requestBuilder =
        new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic());

    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(
        Extension.subjectAlternativeName,
        false,
        new GeneralNames(
            new GeneralName(GeneralName.rfc822Name, "*****@*****.**")));

    requestBuilder.addAttribute(
        PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());

    PKCS10CertificationRequest p10 =
        requestBuilder.build(
            new JcaContentSignerBuilder(sigName).setProvider("BC").build(kp.getPrivate()));

    if (!p10.isSignatureValid(
        new JcaContentVerifierProviderBuilder().setProvider("BC").build(kp.getPublic()))) {
      System.out.println(sigName + ": Failed verify check.");
    } else {
      System.out.println(sigName + ": PKCS#10 request verified.");
    }
    return p10;
  }
  /** 生成密钥对 */
  public static Map<String, String> generateKeyPair() throws Exception {
    /** RSA算法要求有一个可信任的随机数源 */
    SecureRandom sr = new SecureRandom();
    /** 为RSA算法创建一个KeyPairGenerator对象 */
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
    kpg.initialize(KEYSIZE, sr);
    /** 生成密匙对 */
    KeyPair kp = kpg.generateKeyPair();
    /** 得到公钥 */
    Key publicKey = kp.getPublic();
    byte[] publicKeyBytes = publicKey.getEncoded();
    String pub =
        new String(Base64.encodeBase64(publicKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING);
    /** 得到私钥 */
    Key privateKey = kp.getPrivate();
    byte[] privateKeyBytes = privateKey.getEncoded();
    String pri =
        new String(Base64.encodeBase64(privateKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING);

    Map<String, String> map = new HashMap<String, String>();
    map.put("publicKey", pub);
    map.put("privateKey", pri);
    RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
    BigInteger bint = rsp.getModulus();
    byte[] b = bint.toByteArray();
    byte[] deBase64Value = Base64.encodeBase64(b);
    String retValue = new String(deBase64Value);
    map.put("modulus", retValue);
    return map;
  }