2015-11-09 218 views
1

我正在使用AES加密一個字符串,並且想要在其他電腦上解密它。如果我在同一臺PC上執行加密和解密工作。但是對於其他電腦上的解密,我的加密算法正在生成一個「密碼密碼」,這是密鑰的另一端解密所需要的。我不知道如何將密碼轉移到另一端。AES加密和解密Java

這裏是我的代碼

public class AESCrypt { 

    static String plainText; 
    static byte[] plainBytesDecrypted = new byte[1024]; 
    static byte[] cipherBytes = new byte[1024]; 
    static SecretKey key; 
    static Cipher cipher; 

    public AESCrypt() throws NoSuchAlgorithmException { 
     KeyGenerator generator = KeyGenerator.getInstance("AES"); 

     generator.init(128); 
     key = generator.generateKey(); 

    } 

    public static byte[] encryption(String plainBytes) { 

     try { 
      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 

      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); 
      cipher.init(Cipher.ENCRYPT_MODE, key); 
      cipherBytes = cipher.doFinal(plainBytes.getBytes()); 
      System.out.println("Encrypted data : " + new String(cipherBytes)); 

     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
     return cipherBytes; 
    } 

    private static String bytesToHex(byte[] hash) { 

     return DatatypeConverter.printHexBinary(hash); 

    } 

    public static String Decryption() throws InvalidKeyException, IllegalBlockSizeException, InvalidAlgorithmParameterException, BadPaddingException { 

     cipher.init(Cipher.DECRYPT_MODE, key, cipher.getParameters()); 
     plainBytesDecrypted = cipher.doFinal(cipherBytes); 

     System.out.println("Decrypted data : " + new String(plainBytesDecrypted)); 

     return (new String(plainBytesDecrypted)); 
    } 
} 
+0

您是否聽說過[Public-key cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography)? –

回答

0

你在一般的3種選擇:

  • 硬編碼密碼/模式/填充,這樣雙方都知道你總是使用相同的格式。
  • 在祕密消息之前發送密碼/模式/填充,所以另一方知道要初始化的密碼。
  • 使用現有的協議,該協議已經包含了所有這些內容並且安全地執行。例如,您可以在TLS連接內部發送數據。