示例#1
0
  public void initDatabase() throws Exception {

    debug("Initializing database in " + databaseDirectory);

    CryptoManager.InitializationValues vals =
        new CryptoManager.InitializationValues(databaseDirectory, "", "", "secmod.db");
    CryptoManager.initialize(vals);

    CryptoManager cm = CryptoManager.getInstance();
    CryptoToken token = cm.getInternalKeyStorageToken();

    debug("Reading database password from " + databasePasswordFilename);

    String line;
    try (BufferedReader in = new BufferedReader(new FileReader(databasePasswordFilename))) {
      line = in.readLine();
      if (line == null) {
        line = "";
      }
    }
    Password password = new Password(line.toCharArray());

    debug("Logging into security token");

    try {
      token.login(password);
    } finally {
      password.clear();
    }
  }
示例#2
0
  byte[] getEncodedKey(org.mozilla.jss.crypto.PrivateKey pkey) throws Exception {

    CryptoManager cm = CryptoManager.getInstance();
    CryptoToken token = cm.getInternalKeyStorageToken();

    KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3);
    SymmetricKey sk = kg.generate();

    KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
    byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
    IVParameterSpec param = new IVParameterSpec(iv);
    wrapper.initWrap(sk, param);
    byte[] enckey = wrapper.wrap(pkey);

    Cipher c = token.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
    c.initDecrypt(sk, param);
    return c.doFinal(enckey);
  }
示例#3
0
  public byte[] generatePKCS12Data(Password password) throws Exception {

    debug("Generating PKCS #12 data");

    CryptoManager cm = CryptoManager.getInstance();
    CryptoToken token = cm.getInternalKeyStorageToken();
    CryptoStore store = token.getCryptoStore();

    X509Certificate[] certs = store.getCertificates();

    SEQUENCE encSafeContents = new SEQUENCE();
    SEQUENCE safeContents = new SEQUENCE();

    for (int i = 0; i < certs.length; i++) {
      String nickname = certs[i].getNickname();
      debug(" * Certificate: " + nickname);
      try {
        org.mozilla.jss.crypto.PrivateKey prikey = cm.findPrivKeyByCert(certs[i]);

        debug("   Private key exists");
        byte localKeyId[] = addCertBag(certs[i], nickname, safeContents);
        addKeyBag(prikey, certs[i], password, localKeyId, encSafeContents);

      } catch (org.mozilla.jss.crypto.ObjectNotFoundException e) {
        debug("   Private key does not exist");
        addCertBag(certs[i], null, safeContents);
      }
    }

    AuthenticatedSafes authSafes = new AuthenticatedSafes();
    authSafes.addSafeContents(safeContents);
    authSafes.addSafeContents(encSafeContents);

    PFX pfx = new PFX(authSafes);
    pfx.computeMacData(password, null, 5);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    pfx.encode(bos);

    return bos.toByteArray();
  }
  /**
   * Creates and signs an X.509 CertificationRequest.
   *
   * @param info A CertificationRequestInfo (TBSCertificationRequest), which specifies the actual
   *     information of the CertificationRequest.
   * @param privKey The private key with which to sign the certificat.
   * @param signingAlg The algorithm to use to sign the CertificationRequest. It must match the
   *     algorithm specified in the CertificationRequestInfo.
   * @exception IOException If an error occurred while encoding the CertificationRequest.
   * @exception CryptoManager.NotInitializedException Because this operation involves cryptography
   *     (signing), CryptoManager must be initialized before calling it.
   * @exception TokenException If an error occurs on a PKCS #11 token.
   * @exception NoSuchAlgorithmException If the OID for the signing algorithm cannot be located.
   * @exception CertificateException If the signing algorithm specified as a parameter does not
   *     match the one in the CertificationRequest info.
   * @exception InvalidKeyException If the key does not match the signing algorithm.
   * @exception SignatureException If an error occurs while signing the CertificationRequest.
   */
  public CertificationRequest(
      CertificationRequestInfo info,
      java.security.PrivateKey privKey,
      SignatureAlgorithm signingAlg)
      throws IOException, CryptoManager.NotInitializedException, TokenException,
          NoSuchAlgorithmException, CertificateException, InvalidKeyException, SignatureException {
    // make sure key is a Ninja private key
    if (!(privKey instanceof PrivateKey)) {
      throw new InvalidKeyException("Private Key is does not belong to" + " this provider");
    }
    PrivateKey priv = (PrivateKey) privKey;

    // create algId
    if (signingAlg.getSigningAlg() == SignatureAlgorithm.RSASignature) {
      algId = new AlgorithmIdentifier(signingAlg.toOID(), null);
    } else {
      algId = new AlgorithmIdentifier(signingAlg.toOID());
    }

    // encode the cert info
    this.info = info;
    infoEncoding = ASN1Util.encode(info);

    // sign the info encoding
    CryptoManager cm = CryptoManager.getInstance();
    CryptoToken token = priv.getOwningToken();
    Signature sig = token.getSignatureContext(signingAlg);
    sig.initSign(priv);
    sig.update(infoEncoding);
    signature = sig.sign();

    // bundle everything into a SEQUENCE
    sequence = new SEQUENCE();
    sequence.addElement(info);
    sequence.addElement(algId);
    sequence.addElement(new BIT_STRING(signature, 0));
  }
示例#5
0
  public static void main(String args[]) {

    try {

      if (args.length < 2) {
        System.out.println(
            "Usage: FipsTest <dbdir> <fipsmode enter: "
                + "enable OR disable OR chkfips > <password file>");
        return;
      }
      String dbdir = args[0];
      String fipsmode = args[1];

      String password = "";

      if (args.length == 3) {
        password = args[2];
        System.out.println("The password file " + password);
      }

      CryptoManager.InitializationValues vals = new CryptoManager.InitializationValues(dbdir);

      System.out.println("output of Initilization values ");
      System.out.println("Manufacturer ID: " + vals.getManufacturerID());
      System.out.println("Library: " + vals.getLibraryDescription());
      System.out.println("Internal Slot: " + vals.getInternalSlotDescription());
      System.out.println("Internal Token: " + vals.getInternalTokenDescription());
      System.out.println("Key Storage Slot: " + vals.getFIPSKeyStorageSlotDescription());
      System.out.println("Key Storage Token: " + vals.getInternalKeyStorageTokenDescription());
      System.out.println("FIPS Slot: " + vals.getFIPSSlotDescription());
      System.out.println("FIPS Key Storage: " + vals.getFIPSKeyStorageSlotDescription());

      if (fipsmode.equalsIgnoreCase("enable")) {
        vals.fipsMode = CryptoManager.InitializationValues.FIPSMode.ENABLED;
      } else if (fipsmode.equalsIgnoreCase("disable")) {
        vals.fipsMode = CryptoManager.InitializationValues.FIPSMode.DISABLED;
      } else {
        vals.fipsMode = CryptoManager.InitializationValues.FIPSMode.UNCHANGED;
      }

      CryptoManager.initialize(vals);

      CryptoManager cm = CryptoManager.getInstance();

      if (cm.FIPSEnabled() == true) {
        System.out.println("\n\t\tFIPS enabled\n");
      } else {
        System.out.println("\n\t\tFIPS not enabled\n");
      }

      java.util.Enumeration items;
      items = cm.getModules();
      System.out.println("\nListing of Modules:");
      while (items.hasMoreElements()) {
        System.out.println("\t" + ((PK11Module) items.nextElement()).getName());
      }
      CryptoToken tok;
      String tokenName;

      items = cm.getAllTokens();
      System.out.println("\nAll Tokens:");
      while (items.hasMoreElements()) {
        tok = (CryptoToken) items.nextElement();

        System.out.print("\t" + tok.getName());
        if (tok.needsLogin() == true) {
          System.out.println("\t - Needs login.\n");
        } else {
          System.out.println("\t - Does not need login.\n");
        }
      }

      items = cm.getExternalTokens();
      System.out.println("\nExternal Tokens:");
      while (items.hasMoreElements()) {
        System.out.println("\t" + ((CryptoToken) items.nextElement()).getName());
      }

      /* find the Internal Key Storage token */
      if (cm.FIPSEnabled() == true) {
        tokenName = vals.getFIPSSlotDescription();
      } else {
        tokenName = vals.getInternalKeyStorageTokenDescription();
      }

      /* truncate to 32 bytes and remove trailing white space*/
      tokenName = tokenName.substring(0, 32);
      tokenName = tokenName.trim();
      System.out.println("\nFinding the Internal Key Storage token: " + tokenName);
      tok = cm.getTokenByName(tokenName);

      if (((PK11Token) tok).isInternalKeyStorageToken()
          && tok.equals(cm.getInternalKeyStorageToken())) {
        System.out.println(
            "Good, " + tok.getName() + ", knows it is " + "the internal Key Storage Token");
      } else {
        System.out.println(
            "ERROR: " + tok.getName() + ", doesn't know" + " it is the internal key storage token");
      }

      if (!password.equals("")) {
        System.out.println("logging in to the Token: " + tok.getName());
        PasswordCallback cb = new FilePasswordCallback(password);
        tok.login(cb);
        System.out.println("logged in to the Token: " + tok.getName());
      }

      /* find the Internal Crypto token */
      if (cm.FIPSEnabled() == true) {
        tokenName = vals.getFIPSSlotDescription();
      } else {
        tokenName = vals.getInternalTokenDescription();
      }

      /* truncate to 32 bytes and remove trailing white space*/
      tokenName = tokenName.substring(0, 32);
      tokenName = tokenName.trim();
      System.out.println("\nFinding the Internal Crypto token: " + tokenName);
      tok = cm.getTokenByName(tokenName);

      if (((PK11Token) tok).isInternalCryptoToken() && tok.equals(cm.getInternalCryptoToken())) {
        System.out.println("Good, " + tok.getName() + ", knows it is the internal Crypto token");
      } else {
        System.out.println(
            "ERROR: " + tok.getName() + ", doesn't know that it is the internal Crypto token");
      }

      System.exit(0);

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
  public static void main(String argv[]) {

    try {

      if (argv.length > 2 || argv.length < 1) {
        System.out.println("Usage: CertificationRequest <dbdir> [<certfile>]");
        System.exit(0);
      }

      CryptoManager.initialize(argv[0]);
      CryptoManager cm = CryptoManager.getInstance();

      // read in a cert
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(argv[1]));

      CertificationRequest cert =
          (CertificationRequest) CertificationRequest.getTemplate().decode(bis);

      CertificationRequestInfo info = cert.getInfo();

      info.print(System.out);

      // X509CertificationRequest hardcore = cm.findCertByNickname("Hardcore");
      // PublicKey key = hardcore.getPublicKey();

      cert.verify();
      System.out.println("verified");

      FileOutputStream fos = new FileOutputStream("certinfo.der");
      info.encode(fos);
      fos.close();

      // make a new public key
      CryptoToken token = cm.getInternalKeyStorageToken();
      KeyPairGenerator kpg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
      kpg.initialize(512);
      System.out.println("Generating a new key pair...");
      KeyPair kp = kpg.genKeyPair();
      System.out.println("Generated key pair");

      // set the CertificationRequest's public key
      info.setSubjectPublicKeyInfo(kp.getPublic());

      // make new Name
      Name name = new Name();
      name.addCommonName("asldkj");
      name.addCountryName("US");
      name.addOrganizationName("Some Corp");
      name.addOrganizationalUnitName("Some Org Unit");
      name.addLocalityName("Silicon Valley");
      name.addStateOrProvinceName("California");
      info.setSubject(name);

      System.out.println("About to create a new cert request...");
      // create a new cert requestfrom this certReqinfo
      CertificationRequest genCert =
          new CertificationRequest(
              info, kp.getPrivate(), SignatureAlgorithm.RSASignatureWithMD5Digest);
      System.out.println("Created new cert request");

      genCert.verify();
      System.out.println("Cert verifies!");

      fos = new FileOutputStream("gencert.der");
      genCert.encode(fos);
      fos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /**
  * Verifies the signature on this CertificationRequest, using the given public key. Does not
  * indicate the CertificationRequest is valid at any specific time.
  */
 public void verify(PublicKey key)
     throws InvalidKeyException, CryptoManager.NotInitializedException, NoSuchAlgorithmException,
         CertificateException, TokenException, SignatureException {
   CryptoManager cm = CryptoManager.getInstance();
   verify(key, cm.getInternalCryptoToken());
 }
示例#8
0
  public static void main(String[] args) {

    try {

      // Read arguments
      if (args.length != 3) {
        System.out.println("Usage: PFX <dbdir> <infile> <outfile>");
        System.exit(-1);
      }

      // open input file for reading
      FileInputStream infile = null;
      try {
        infile = new FileInputStream(args[1]);
      } catch (FileNotFoundException f) {
        System.out.println("Cannot open file " + args[1] + " for reading: " + f.getMessage());
        return;
      }
      int certfile = 0;

      // initialize CryptoManager. This is necessary because there is
      // crypto involved with decoding a PKCS #12 file
      CryptoManager.initialize(args[0]);
      CryptoManager manager = CryptoManager.getInstance();

      // Decode the P12 file
      PFX.Template pfxt = new PFX.Template();
      PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(infile, 2048));
      System.out.println("Decoded PFX");

      // print out information about the top-level PFX structure
      System.out.println("Version: " + pfx.getVersion());
      AuthenticatedSafes authSafes = pfx.getAuthSafes();
      SEQUENCE safeContentsSequence = authSafes.getSequence();
      System.out.println("AuthSafes has " + safeContentsSequence.size() + " SafeContents");

      // Get the password for the old file
      System.out.println("Enter password: "******"Enter new password:"******"AuthSafes verifies correctly.");
      } else {
        System.out.println("AuthSafes failed to verify because: " + sb);
      }

      // Create a new AuthenticatedSafes. As we read the contents of the
      // old authSafes, we will store them into the new one.  After we have
      // cycled through all the contents, they will all have been copied into
      // the new authSafes.
      AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();

      // Loop over contents of the old authenticated safes
      // for(int i=0; i < asSeq.size(); i++) {
      for (int i = 0; i < safeContentsSequence.size(); i++) {

        // The safeContents may or may not be encrypted.  We always send
        // the password in.  It will get used if it is needed.  If the
        // decryption of the safeContents fails for some reason (like
        // a bad password), then this method will throw an exception
        SEQUENCE safeContents = authSafes.getSafeContentsAt(pass, i);

        System.out.println("\n\nSafeContents #" + i + " has " + safeContents.size() + " bags");

        // Go through all the bags in this SafeContents
        for (int j = 0; j < safeContents.size(); j++) {
          SafeBag safeBag = (SafeBag) safeContents.elementAt(j);

          // The type of the bag is an OID
          System.out.println("\nBag " + j + " has type " + safeBag.getBagType());

          // look for bag attributes
          SET attribs = safeBag.getBagAttributes();
          if (attribs == null) {
            System.out.println("Bag has no attributes");
          } else {
            for (int b = 0; b < attribs.size(); b++) {
              Attribute a = (Attribute) attribs.elementAt(b);
              if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
                // the friendly name attribute is a nickname
                BMPString bs =
                    (BMPString)
                        ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
                System.out.println("Friendly Name: " + bs);
              } else if (a.getType().equals(SafeBag.LOCAL_KEY_ID)) {
                // the local key id is used to match a key
                // to its cert.  The key id is the SHA-1 hash of
                // the DER-encoded cert.
                OCTET_STRING os =
                    (OCTET_STRING)
                        ((ANY) a.getValues().elementAt(0)).decodeWith(OCTET_STRING.getTemplate());
                System.out.println("LocalKeyID:");
                /*
                                     AuthenticatedSafes.
                                         print_byte_array(os.toByteArray());
                */
              } else {
                System.out.println("Unknown attribute type: " + a.getType().toString());
              }
            }
          }

          // now look at the contents of the bag
          ASN1Value val = safeBag.getInterpretedBagContent();

          if (val instanceof PrivateKeyInfo) {
            // A PrivateKeyInfo contains an unencrypted private key
            System.out.println("content is PrivateKeyInfo");
          } else if (val instanceof EncryptedPrivateKeyInfo) {
            // An EncryptedPrivateKeyInfo is, well, an encrypted
            // PrivateKeyInfo. Usually, strong crypto is used in
            // an EncryptedPrivateKeyInfo.
            EncryptedPrivateKeyInfo epki = ((EncryptedPrivateKeyInfo) val);
            System.out.println(
                "content is EncryptedPrivateKeyInfo, algoid:"
                    + epki.getEncryptionAlgorithm().getOID());

            // Because we are in a PKCS #12 file, the passwords are
            // char-to-byte converted in a special way.  We have to
            // use the special converter class instead of the default.
            PrivateKeyInfo pki = epki.decrypt(pass, new org.mozilla.jss.pkcs12.PasswordConverter());

            // import the key into the key3.db
            CryptoToken tok = manager.getTokenByName("Internal Key Storage Token");
            CryptoStore store = tok.getCryptoStore();
            tok.login(new ConsolePasswordCallback());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            pki.encode(baos);
            store.importPrivateKey(baos.toByteArray(), PrivateKey.RSA);

            // re-encrypt the PrivateKeyInfo with the new password
            // and random salt
            byte[] salt = new byte[PBEAlgorithm.PBE_SHA1_DES3_CBC.getSaltLength()];
            JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
            rand.nextBytes(salt);
            epki =
                EncryptedPrivateKeyInfo.createPBE(
                    PBEAlgorithm.PBE_SHA1_DES3_CBC, newPass, salt, 1, new PasswordConverter(), pki);

            // Overwrite the previous EncryptedPrivateKeyInfo with
            // this new one we just created using the new password.
            // This is what will get put in the new PKCS #12 file
            // we are creating.
            safeContents.insertElementAt(
                new SafeBag(safeBag.getBagType(), epki, safeBag.getBagAttributes()), i);
            safeContents.removeElementAt(i + 1);

          } else if (val instanceof CertBag) {
            System.out.println("content is CertBag");
            CertBag cb = (CertBag) val;
            if (cb.getCertType().equals(CertBag.X509_CERT_TYPE)) {
              // this is an X.509 certificate
              OCTET_STRING os = (OCTET_STRING) cb.getInterpretedCert();
              Certificate cert =
                  (Certificate) ASN1Util.decode(Certificate.getTemplate(), os.toByteArray());
              cert.getInfo().print(System.out);
            } else {
              System.out.println("Unrecognized cert type");
            }
          } else {
            System.out.println("content is ANY");
          }
        }

        // Add the new safe contents to the new authsafes
        if (authSafes.safeContentsIsEncrypted(i)) {
          newAuthSafes.addEncryptedSafeContents(
              authSafes.DEFAULT_KEY_GEN_ALG,
              newPass,
              null,
              authSafes.DEFAULT_ITERATIONS,
              safeContents);
        } else {
          newAuthSafes.addSafeContents(safeContents);
        }
      }

      // Create new PFX from the new authsafes
      PFX newPfx = new PFX(newAuthSafes);

      // Add a MAC to the new PFX
      newPfx.computeMacData(newPass, null, PFX.DEFAULT_ITERATIONS);

      // write the new PFX out to a file
      FileOutputStream fos = new FileOutputStream(args[2]);
      newPfx.encode(fos);
      fos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }