private void testKeyFactory() throws Exception {
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");

    ECCurve curve =
        new ECCurve.Fp(
            new BigInteger(
                "883423532389192164791648750360308885314476597252960362792450860609699839"), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger(
                "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    ECParameterSpec ecSpec =
        new ECParameterSpec(
            curve,
            curve.decodePoint(
                Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger(
                "883423532389192164791648750360308884807550341691627752275345424702807307")); // n

    ConfigurableProvider config = (ConfigurableProvider) Security.getProvider("SC");

    config.setParameter(ConfigurableProvider.EC_IMPLICITLY_CA, ecSpec);

    g.initialize(null, new SecureRandom());

    KeyPair p = g.generateKeyPair();

    ECPrivateKey sKey = (ECPrivateKey) p.getPrivate();
    ECPublicKey vKey = (ECPublicKey) p.getPublic();

    KeyFactory fact = KeyFactory.getInstance("ECDSA", "SC");

    vKey = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), null));
    sKey = (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), null));

    testECDSA(sKey, vKey);

    testBCParamsAndQ(sKey, vKey);
    testEC5Params(sKey, vKey);

    testEncoding(sKey, vKey);

    ECPublicKey vKey2 = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), ecSpec));
    ECPrivateKey sKey2 =
        (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), ecSpec));

    if (!vKey.equals(vKey2) || vKey.hashCode() != vKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    if (!sKey.equals(sKey2) || sKey.hashCode() != sKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    // check we can get specs.
    fact.getKeySpec(vKey, java.security.spec.ECPublicKeySpec.class);

    fact.getKeySpec(sKey, java.security.spec.ECPrivateKeySpec.class);
  }
Exemple #2
0
 private static void testPrivate(KeyFactory kf, PrivateKey key) throws Exception {
   System.out.println("Testing private key...");
   PrivateKey key2 = (PrivateKey) kf.translateKey(key);
   KeySpec keySpec = kf.getKeySpec(key, ECPrivateKeySpec.class);
   PrivateKey key3 = kf.generatePrivate(keySpec);
   KeySpec pkcs8Spec = kf.getKeySpec(key, PKCS8EncodedKeySpec.class);
   PrivateKey key4 = kf.generatePrivate(pkcs8Spec);
   KeySpec pkcs8Spec2 = new PKCS8EncodedKeySpec(key.getEncoded());
   PrivateKey key5 = kf.generatePrivate(pkcs8Spec2);
   testKey(key, key);
   testKey(key, key2);
   testKey(key, key3);
   testKey(key, key4);
   testKey(key, key5);
 }
Exemple #3
0
 private static void testPublic(KeyFactory kf, PublicKey key) throws Exception {
   System.out.println("Testing public key...");
   PublicKey key2 = (PublicKey) kf.translateKey(key);
   KeySpec keySpec = kf.getKeySpec(key, ECPublicKeySpec.class);
   PublicKey key3 = kf.generatePublic(keySpec);
   KeySpec x509Spec = kf.getKeySpec(key, X509EncodedKeySpec.class);
   PublicKey key4 = kf.generatePublic(x509Spec);
   KeySpec x509Spec2 = new X509EncodedKeySpec(key.getEncoded());
   PublicKey key5 = kf.generatePublic(x509Spec2);
   testKey(key, key);
   testKey(key, key2);
   testKey(key, key3);
   testKey(key, key4);
   testKey(key, key5);
 }
  public static PublicKeyRecord createNew(KeyPair kp)
      throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory fact = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);

    int id = 0;

    try {
      Connection conn = DatabaseConnection.getConn();
      String sql = "insert into publickey modulus = ?, exponent = ?";
      PreparedStatement stmt = conn.prepareStatement(sql);

      stmt.setString(1, pub.getModulus().toString());

      stmt.setString(2, pub.getPublicExponent().toString());
      stmt.executeUpdate();
      ResultSet generatedKeys = stmt.getGeneratedKeys();
      if (generatedKeys.next()) {
        id = generatedKeys.getInt(1);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }

    return get(id);
  }
 private void saveKey() {
   PublicKey publicKey = keyPair.getPublic();
   PrivateKey privateKey = keyPair.getPrivate();
   KeyFactory keyFactory;
   try {
     keyFactory = KeyFactory.getInstance("DSA");
     DSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(privateKey, DSAPrivateKeySpec.class);
     DSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(publicKey, DSAPublicKeySpec.class);
     this.account.setKey("otr_x", privateKeySpec.getX().toString(16));
     this.account.setKey("otr_g", privateKeySpec.getG().toString(16));
     this.account.setKey("otr_p", privateKeySpec.getP().toString(16));
     this.account.setKey("otr_q", privateKeySpec.getQ().toString(16));
     this.account.setKey("otr_y", publicKeySpec.getY().toString(16));
   } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
     e.printStackTrace();
   }
 }
 public static void savePublicKeyInFile(String path, PublicKey key) {
   try {
     KeyFactory fac = KeyFactory.getInstance("RSA");
     RSAPublicKeySpec RSAspec = fac.getKeySpec(key, RSAPublicKeySpec.class);
     FileOutputStream file3 = new FileOutputStream(path);
     ObjectOutputStream obj_stream = new ObjectOutputStream(file3);
     obj_stream.writeObject(RSAspec.getModulus());
     obj_stream.writeObject(RSAspec.getPublicExponent());
   } catch (Exception ex) {
     System.err.println("Probeleme de sauvegarde de la cle public dans un fichier: " + ex);
   }
 }
Exemple #7
0
 static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
   if (key instanceof DHPublicKey) {
     DHPublicKey dhKey = (DHPublicKey) key;
     DHParameterSpec params = dhKey.getParams();
     return new DHPublicKeySpec(dhKey.getY(), params.getP(), params.getG());
   }
   try {
     KeyFactory factory = JsseJce.getKeyFactory("DH");
     return (DHPublicKeySpec) factory.getKeySpec(key, DHPublicKeySpec.class);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  public void run() {

    boolean loginSuccessfull = false;
    int loginAttempts = 0;

    try {

      KeyFactory fact = KeyFactory.getInstance("RSA");
      RSAPublicKeySpec pub = fact.getKeySpec(a.getPublicKey(), RSAPublicKeySpec.class);

      socketWrapper.write(pub.getModulus().toString());
      if (!socketWrapper.read().equals("got")) return;
      socketWrapper.write(pub.getPublicExponent().toString());

      RSAEncryption rsa = new RSAEncryption();
      String msg = rsa.encrypt("[ENCRYPTED HELLO]", a.getPrivateKey());
      socketWrapper.write(msg);

      String user = null, pass = null;

      socketWrapper.write(rsa.encrypt("login as: ", a.getPrivateKey()));
      user = rsa.decrypt(socketWrapper.read(), a.getPrivateKey());
      System.out.println("[FROM CLIENT] " + user);

      while (!loginSuccessfull && loginAttempts < 1) {

        if (loginAttempts > 0)
          socketWrapper.write(rsa.encrypt("login failed.\npassword: "******"password: "******"[FROM CLIENT] " + pass);

        if (accessManager.isPasswordCorrect(user, pass)) {
          loginSuccessfull = true;
          break;
        } else {
          loginAttempts++;
        }
      }

      if (!loginSuccessfull) {
        if (!user.equals("admin")) accessManager.lockUserAccount(user);

        socketWrapper.write(
            rsa.encrypt(
                "maximum login attempts exeeded. Account is locked now. Disconnect\n",
                a.getPrivateKey()));
        clientSocket.close();
        return;
      } else {
        if (!accessManager.isAccountUnlocked(user)) {
          socketWrapper.write(
              rsa.encrypt("account locked. Contact administrator\n", a.getPrivateKey()));
          clientSocket.close();
          return;
        }
      }

      socketWrapper.write(
          rsa.encrypt("logged in as \"" + user + "\" successfully\n", a.getPrivateKey()));

      while (true) {
        String userInput = rsa.decrypt(socketWrapper.read(), a.getPrivateKey());

        if (userInput.equals("quit")) {
          System.out.println("[GOT \"quit\" FROM USER]");
          socketWrapper.write(rsa.encrypt("[quit]", a.getPrivateKey()));
          break;
        }

        if (userInput.equals("ok")) {
          socketWrapper.write(rsa.encrypt("ok", a.getPrivateKey()));
          continue;
        }

        socketWrapper.write(
            rsa.encrypt(commandProcessor.processCommand(user, userInput), a.getPrivateKey()));
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /**
  * Generates X509 encoded public key bytes from a given public key.
  *
  * @param publicKey the public key
  * @return generated public key bytes
  * @throws Exception if any errors occur
  */
 public static byte[] generateX509PublicKey(PublicKey publicKey) throws Exception {
   X509EncodedKeySpec x509EncodedPublicKey =
       KEY_FACTORY.getKeySpec(publicKey, X509EncodedKeySpec.class);
   return x509EncodedPublicKey.getEncoded();
 }
 private RSAPublicKeySpec getPublicKeySpec(PublicKey publicKey)
     throws NoSuchAlgorithmException, InvalidKeySpecException {
   KeyFactory keyFac = KeyFactory.getInstance("RSA");
   return keyFac.getKeySpec(publicKey, RSAPublicKeySpec.class);
 }