Java中AES的解密

时间:2010-10-24 11:45:49

标签: java encryption aes

法语:slt,评论je peut faire le dechiffrement en utilisant AES c'est mon code
英文: 嗨,我该如何使用AES进行解密?这是我的代码:

public class NewClass1{

    private Key key;

    private void generateKey() throws NoSuchAlgorithmException{
        KeyGenerator generator;
        generator = KeyGenerator.getInstance("AES");
        generator.init(new SecureRandom());
        key = generator.generateKey();
    }

    private String decrypt(String encrypted) throws InvalidKeyException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        IllegalBlockSizeException,
        BadPaddingException,
        IOException{

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] raw = decoder.decodeBuffer(encrypted);
        byte[] stringBytes = cipher.doFinal(raw);
        // converts the decoded message to a String
        String clear = new String(stringBytes);
        return clear;
    }

    public NewClass1(String encrypted){
        try{
            System.out.println("encrypted message: " + encrypted);
            generateKey();
            String decrypted = decrypt(encrypted);
            System.out.println("decrypted message: " + decrypted);
        } catch(NoSuchAlgorithmException e){
            e.printStackTrace();
        } catch(NoSuchPaddingException e){
            e.printStackTrace();
        } catch(InvalidKeyException e){
            e.printStackTrace();
        } catch(UnsupportedEncodingException e){
            e.printStackTrace();
        } catch(IllegalBlockSizeException e){
            e.printStackTrace();
        } catch(BadPaddingException e){
            e.printStackTrace();
        } catch(IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        new NewClass1("vbfhdhhhjhtrrrrrrrrrrrrrrjrdfes");
    }
}

1 个答案:

答案 0 :(得分:3)

这里有一些非常基本的错误。您的代码暗示“vbfhdhhhjhtrrrrrrrrrrrrrrjrdfes”是AES加密结果的base64编码。不是。您的代码还会生成随机解密键。那不行。我建议从一些Wikipedia articles on encryption开始。