Ejemplo n.º 1
0
 private X509Certificate buildSignedCert(String domain, KeyPair _keyPair) throws Exception {
   PrivateKey privateRootKey =
       (PrivateKey)
           keystore.getKey(Configuration.getRootCaName(), KEYSTORE_PASSWORD.toCharArray());
   X509v3CertificateBuilder certificateBuilder = createX509v3CertificateBuilder(domain, _keyPair);
   return createX509Certificate(certificateBuilder, privateRootKey);
 }
Ejemplo n.º 2
0
 /**
  * Method decrypts the data with the RSA private key corresponding to this certificate (which was
  * used to encrypt it). Decryption will be done with keystore
  *
  * @param data data to be decrypted.
  * @param token index of authentication token
  * @param pin PIN code
  * @return decrypted data.
  * @throws DigiDocException for all decryption errors
  */
 public byte[] decrypt(byte[] data, int token, String pin) throws DigiDocException {
   try {
     if (m_keyStore == null)
       throw new DigiDocException(
           DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null);
     String alias = getTokenName(token);
     if (alias == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null);
     // get key
     if (m_logger.isDebugEnabled())
       m_logger.debug(
           "loading key: " + alias + " passwd-len: " + ((pin != null) ? pin.length() : 0));
     Key key = m_keyStore.getKey(alias, pin.toCharArray());
     if (m_logger.isDebugEnabled())
       m_logger.debug("Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL"));
     if (key == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid password for token: " + alias, null);
     Cipher cipher = Cipher.getInstance("RSA");
     cipher.init(Cipher.DECRYPT_MODE, key);
     byte[] decdata = cipher.doFinal(data);
     if (m_logger.isDebugEnabled())
       m_logger.debug("Decrypted len: " + ((decdata != null) ? decdata.length : 0));
     return decdata;
   } catch (Exception ex) {
     m_logger.error("Error decrypting: " + ex);
   }
   return null;
 }
Ejemplo n.º 3
0
 void assertPrivateKs(File file, String pass, String alias) throws Exception {
   KeyStore ks = loadKeyStore("jceks", file, alias);
   List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
   assertEquals(2, aliases.size());
   Certificate cert = ks.getCertificate(alias + ".crt");
   assertNotNull(cert);
   assertEquals("X.509", cert.getType());
   assertTrue(ks.isKeyEntry(alias + ".key"));
   assertTrue(ks.isCertificateEntry(alias + ".crt"));
   Key key = ks.getKey(alias + ".key", pass.toCharArray());
   assertNotNull(key);
   assertEquals("RSA", key.getAlgorithm());
 }
Ejemplo n.º 4
0
  /**
   * Initialisation if a supplied key is defined in the properties. This supplied key must be in a
   * keystore which can be generated using the keystoreGenerator file in demos. The keystore must be
   * on the classpath to find it.
   *
   * @throws KeyStoreException
   * @throws Exception
   * @throws IOException
   * @throws NoSuchAlgorithmException
   * @throws CertificateException
   * @throws UnrecoverableKeyException
   */
  private void initConfiguredKey() throws Exception {
    InputStream inputStream = null;
    // must not use default keystore type - as does not support secret keys
    KeyStore store = KeyStore.getInstance("JCEKS");

    SecretKey tempKey = null;
    try {
      // load in keystore using this thread's classloader
      inputStream =
          Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreName);
      if (inputStream == null) inputStream = new FileInputStream(keyStoreName);
      // we can't find a keystore here -
      if (inputStream == null) {
        throw new Exception(
            "Unable to load keystore " + keyStoreName + " ensure file is on classpath");
      }
      // we have located a file lets load the keystore
      try {
        store.load(inputStream, storePassword.toCharArray());
        // loaded keystore - get the key
        tempKey = (SecretKey) store.getKey(alias, keyPassword.toCharArray());
      } catch (IOException e) {
        throw new Exception("Unable to load keystore " + keyStoreName + ": " + e);
      } catch (NoSuchAlgorithmException e) {
        throw new Exception("No Such algorithm " + keyStoreName + ": " + e);
      } catch (CertificateException e) {
        throw new Exception("Certificate exception " + keyStoreName + ": " + e);
      }

      if (tempKey == null)
        throw new Exception("Unable to retrieve key '" + alias + "' from keystore " + keyStoreName);
      // set the key here
      setSecretKey(tempKey);

      if (symAlgorithm.equals(DEFAULT_SYM_ALGO)) symAlgorithm = tempKey.getAlgorithm();

      // set the fact we are using a supplied key
      suppliedKey = true;
      queue_down = queue_up = false;
    } finally {
      Util.close(inputStream);
    }
  }
Ejemplo n.º 5
0
  public void main(Provider p) throws Exception {

    /*
     * Use Solaris SPARC 11.2 or later to avoid an intermittent failure
     * when running SunPKCS11-Solaris (8044554)
     */
    if (p.getName().equals("SunPKCS11-Solaris")
        && System.getProperty("os.name").equals("SunOS")
        && System.getProperty("os.arch").equals("sparcv9")
        && System.getProperty("os.version").compareTo("5.11") <= 0
        && getDistro().compareTo("11.2") < 0) {

      System.out.println(
          "SunPKCS11-Solaris provider requires " + "Solaris SPARC 11.2 or later, skipping");
      return;
    }

    long start = System.currentTimeMillis();
    provider = p;
    data = new byte[2048];
    new Random().nextBytes(data);
    KeyStore ks = getKeyStore();
    KeyFactory kf = KeyFactory.getInstance("RSA", provider);
    for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
      String alias = (String) e.nextElement();
      if (ks.isKeyEntry(alias)) {
        System.out.println("* Key " + alias + "...");
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password);
        PublicKey publicKey = ks.getCertificate(alias).getPublicKey();
        privateKey = (PrivateKey) kf.translateKey(privateKey);
        publicKey = (PublicKey) kf.translateKey(publicKey);
        test(privateKey, publicKey);
      }
    }
    long stop = System.currentTimeMillis();
    System.out.println("All tests passed (" + (stop - start) + " ms).");
  }
Ejemplo n.º 6
0
  @Test
  public void testKeyStore()
      throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException,
          InvalidKeySpecException, UnrecoverableKeyException {
    File serverPem = getTempFile("server/cert.pem");
    File keyPem = getTempFile("server/key.pem");
    KeyStore keystore = createKeyStore();

    KeyStoreUtil.updateWithServerPems(keystore, serverPem, keyPem, "RSA", new char[0]);

    Enumeration<String> aliases = keystore.aliases();
    String alias = aliases.nextElement();
    assertFalse(aliases.hasMoreElements());

    assertTrue(alias.contains("server"));

    X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
    cert.checkValidity();
    assertEquals(cert.getSubjectDN().getName(), SERVER_CERT_SUBJECT_DN);
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) keystore.getKey(alias, new char[0]);
    assertEquals("RSA", key.getAlgorithm());
    RSAPublicKey pubKey = (RSAPublicKey) cert.getPublicKey();
    assertEquals("RSA", pubKey.getAlgorithm());
  }
Ejemplo n.º 7
0
 /**
  * Method returns a digital signature. It finds the RSA private key object from the active token
  * and then signs the given data with this key and RSA mechanism.
  *
  * @param digest digest of the data to be signed.
  * @param token token index
  * @param passwd users pin code or in case of pkcs12 file password
  * @param sig Signature object to provide info about desired signature method
  * @return an array of bytes containing digital signature.
  * @throws DigiDocException if signing the data fails.
  */
 public byte[] sign(byte[] xml, int token, String passwd, Signature sig) throws DigiDocException {
   try {
     if (m_keyStore == null)
       throw new DigiDocException(
           DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null);
     String alias = getTokenName(token);
     if (alias == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null);
     // get key
     if (m_logger.isDebugEnabled())
       m_logger.debug(
           "loading key: " + alias + " passwd-len: " + ((passwd != null) ? passwd.length() : 0));
     Key key = m_keyStore.getKey(alias, passwd.toCharArray());
     if (m_logger.isDebugEnabled())
       m_logger.debug("Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL"));
     if (key == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid password for token nr: " + token, null);
     String sigMeth = null;
     if (sig != null
         && sig.getSignedInfo() != null
         && sig.getSignedInfo().getSignatureMethod() != null)
       sigMeth = sig.getSignedInfo().getSignatureMethod();
     if (m_logger.isDebugEnabled())
       m_logger.debug("Signing\n---\n" + new String(xml) + "\n---\n method: " + sigMeth);
     java.security.Signature instance = sigMeth2SigSignatureInstance(sig, key);
     if (m_logger.isDebugEnabled())
       m_logger.debug("Signature instance: " + ((instance != null) ? "OK" : "NULL"));
     instance.initSign((PrivateKey) key);
     instance.update(xml);
     byte[] signature = instance.sign();
     boolean bEcCvcKey = isCvcEcKey(sig);
     if (m_logger.isDebugEnabled())
       m_logger.debug(
           "Signature algorithm: "
               + key.getAlgorithm()
               + " siglen: "
               + signature.length
               + " ec-key: "
               + bEcCvcKey);
     if (bEcCvcKey) {
       int nKeyLen = ((ECPrivateKey) key).getParams().getCurve().getField().getFieldSize();
       int nReqLen = ((int) Math.ceil((double) nKeyLen / 8)) * 2;
       int nSigLen = signature.length;
       if (m_logger.isDebugEnabled())
         m_logger.debug("EC Signature length: " + nSigLen + " required: " + nReqLen);
       if (nSigLen < nReqLen) {
         if (m_logger.isDebugEnabled())
           m_logger.debug("Padding EC signature length: " + nSigLen + " to required: " + nReqLen);
         byte[] padsig = new byte[nReqLen];
         System.arraycopy(signature, 0, padsig, (nReqLen - nSigLen) / 2, nSigLen / 2);
         System.arraycopy(
             signature, nSigLen / 2, padsig, (nReqLen / 2) + (nReqLen - nSigLen) / 2, nSigLen / 2);
         signature = padsig;
       }
     }
     if (m_logger.isDebugEnabled() && signature != null)
       m_logger.debug(
           "Signature len: "
               + signature.length
               + "\n---\n sig: "
               + ConvertUtils.bin2hex(signature));
     return signature;
   } catch (DigiDocException ex) {
     m_logger.error("DigiDoc Error signing: " + ex);
     throw ex;
   } catch (Exception ex) {
     m_logger.error("Error signing: " + ex);
   }
   return null;
 }