使用密码java加密消息

时间:2016-12-27 16:31:07

标签: java encryption

这是一个学校项目,我必须使用密码加密邮件。所以我建立了与服务器的连接,看起来一切正常,但在cipher.init(Cipher.ENCRYPT_MODE, secret);行中,它打破了所有代码,所以在此之前我无法创建sout,有人帮帮我吗?

try {
      String sName = "localhost";
      int port = 8080;

      Socket client = new Socket(sName, port);
      OutputStream os = client.getOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter(os);
      BufferedWriter bw = new BufferedWriter(osw);

      //String password = null;
      String password = fieldPassword.getText();
      char[] a = password.toCharArray();
      byte[] salt = new byte[256];

      SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
      KeySpec spec = new PBEKeySpec(a, salt, 65536, 256);
      SecretKey tmp = factory.generateSecret(spec);
      SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");


      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secret);
      String msg = jTextField2.getText();
      byte[] text = msg.getBytes();
      byte[] ciphertext = cipher.doFinal(text);

      String hex=DatatypeConverter.printHexBinary(ciphertext);
      System.out.println(hex);

      String sendMessage = "{'command':'send','dst':'" + jTextField1.getText() + "','msgencrypt':'" + hex  +"'}";`this is json to send to the server`
      bw.write(sendMessage);
      bw.flush();
 } catch (IOException ex) {
      Logger.getLogger(NewJFrame3.class.getName()).log(Level.SEVERE, null, ex);
 }catch (Exception e){ 
 }

1 个答案:

答案 0 :(得分:0)

您正在请求密钥大小为 256位的AES密钥,其中包含:

KeySpec spec = new PBEKeySpec(a, salt, 65536, 256);

但由于import/export regulations未修补的 JVM将不允许使用这么大的AES密钥。

Eigther使用无限强度管辖权政策文件修补您的JVM,或使用 128位密钥尝试:

KeySpec spec = new PBEKeySpec(a, salt, 65536, 128);