簡體   English   中英

使用密碼java加密消息

[英]encrypt a message with an password java

這是一個學校項目,我必須使用密碼加密消息。 所以我建立了與服務器的連接,看起來一切正常,但在行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){ 
 }

您正在請求密鑰大小為256位的AES密鑰:

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

但是由於導入/導出規定未修補的 JVM將不允許使用這么大的AES密鑰。

Eigther使用Unlimited Strength Jurisdiction Policy文件修補您的JVM,或使用以下方法嘗試使用128位密鑰:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM