如何打印AES加密的字符串,以便在其他应用程序中重用?

时间:2016-06-05 20:20:50

标签: java encryption cryptography bytearray aes

我写了两个小的java应用程序。第一个用随机密钥加密字符串,并通过post-request将密钥发送到我的服务器。加密的字符串也将通过post-request发送到另一台服务器。现在我想访问第二个服务器手动复制加密的字符串并使用我的第二个应用程序解密它。但似乎第二个应用程序中的textArea无法处理很多特殊符号。

让我们举一个例子: 字符串“TESTDATA”使用随机生成的密钥“28r94sabf614atuhp1rhtprq8q”的MD5消化进行AES加密。到达我的服务器的结果将是“ïë>1Ùd>íÔâªOMT”。当我将其粘贴到第二个应用程序的textArea并尝试解密它时会抛出此异常:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:913)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at GUI.decrypt(GUI.java:108)

这是我第一次申请的重要代码:

public static void main(String[] args) {
    String data = getData();
    String key = generateKey();
    byte[] encrypted = encryptData(data, key);
    String str_encrypted = new String(encrypted);
    String url = pushToServer(str_encrypted);
}

private static byte[] encryptData(String data, String key) {

    try {
        MessageDigest md = MessageDigest.getInstance("MD5");

        md.update(key.getBytes("UTF-8"));
        byte[] digest = md.digest();

        Cipher c = Cipher.getInstance("AES");
        SecretKeySpec k = new SecretKeySpec(digest, "AES");
        c.init(Cipher.ENCRYPT_MODE, k);

        byte[] tobeencrypted = data.getBytes("UTF-8");

        return c.doFinal(tobeencrypted);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

这是我的第二个应用程序的重要代码:

btnDecrypt.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String data = textArea.getText();
        String key = txtDecryptionkey.getText();

        textArea.setText(decrypt(data, key));

    }
});

-

private static String decrypt(String data, String key){
    try {


    MessageDigest md = MessageDigest.getInstance("MD5");

    md.update(key.getBytes("UTF-8"));
    byte[] digest = md.digest();

    Cipher c = Cipher.getInstance("AES");
    SecretKeySpec k = new SecretKeySpec(digest, "AES");
    c.init(Cipher.DECRYPT_MODE, k);

    byte[] decrypt = c.doFinal(data.getBytes("UTF-8"));

    String decrypted = new String(decrypt);

    return decrypted;
    } catch (Exception e){
        e.printStackTrace();
        return "Something went wrong";
    }
}

0 个答案:

没有答案