Ejemplo n.º 1
0
  public static JSONObject getRSAKeys(String address, boolean auto_generate) throws Exception {
    String privateKeyFilename = "resources/db/ck-" + address;

    if (!(new File(privateKeyFilename)).exists()) {
      if (!auto_generate) return null;

      // init a rsa key file for current address
      JSONObject keyMap = RSACoder.initKey();
      logger.info("Generated new keys: " + keyMap.toString());

      if (!exportTextToFile(keyMap.toString(), privateKeyFilename)) {
        logger.error("Failed to save generated RSA keys to " + privateKeyFilename);
        return null;
      }
    }
    String tmpKeyStr = Util.readTextFile(privateKeyFilename);
    if (tmpKeyStr == null) {
      logger.error("Failed to get RSA keys from " + privateKeyFilename);
      return null;
    }

    JSONObject keyMap = new JSONObject(tmpKeyStr);

    return keyMap;
  }
  @Test
  public void httpclientTest() {
    // 创建默认的httpClient实例.
    CloseableHttpClient httpclient = HttpClients.createDefault();

    // 创建httppost
    HttpPost httppost = new HttpPost(POST_URL);

    String secrectKey = null;
    try {
      secrectKey = AESCoder.initKeyString();
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try {

      byte[] secrectKyeByteArray = secrectKey.getBytes();
      byte[] encryptByPublicKey = RSACoder.encryptByPublicKey(secrectKyeByteArray, publicKey);

      httppost.setEntity(new ByteArrayEntity(encryptByPublicKey));
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    System.out.println("executing request " + httppost.getURI());

    CloseableHttpResponse response = null;
    try {
      response = httpclient.execute(httppost);

      //			if (entity != null) {
      //                System.out.println("--------------------------------------");
      //                String responseString = EntityUtils.toString(entity);
      //				System.out.println("Response content: " + responseString);
      //                System.out.println("--------------------------------------");

      try {

        byte[] input =
            AESCoder.decrypt(IOUtils.toByteArray(response.getEntity().getContent()), secrectKey);

        String serverData = new String(input);

        System.out.println("server data: " + serverData);

        org.junit.Assert.assertNotNull(input);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      //            }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    try {
      httpclient.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }