【问题标题】:AES Encryption algorithm output string length (String) error?AES加密算法输出字符串长度(String)错误?
【发布时间】:2015-04-10 14:30:08
【问题描述】:
 public static String encryptKey(String key,String text) throws CryptoException 
    {
        String key1=null;
        try {

            System.out.println("input parameters length  "+key.length()+ " " +text.length());
            System.out.println("input parameters value "+key+ " " +text);
            Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);

            cipher.init(Cipher.ENCRYPT_MODE, secretKey);             
            byte[] inputBytes=text.getBytes();
           //System.out.println(inputBytes.length);
            byte[] outputBytes = cipher.doFinal(inputBytes);
           // key= WriteArray.bytesToString(outputBytes);  
           key1=outputBytes.toString();


            System.out.println("output parameters  "+key1.length()+" "+ text.length());
            System.out.println("output parameters value "+key1+ " " +text);
        } 

输入输出字符串长度不同。为什么会这样?

是转换字符串到字节数组转换的问题吗?输出如下所示。

--------------------------------------
Level 1 Encryption Started
input parameters length  16 16
input parameters value 5iafq1b7d8i4hedu vg322qcfmnjbp3nj
output parameters  11 16
output parameters value [B@35851384 vg322qcfmnjbp3nj
--------------------------------------
Level 2 Encryption Started
input parameters length  16 11
input parameters value tvqfpjpul28ovo5c [B@35851384
output parameters  11 11
output parameters value [B@649d209a [B@35851384
--------------------------------------

【问题讨论】:

标签: java encryption aes encryption-symmetric


【解决方案1】:

永远不要将加密数据视为字符串。它是二进制数据,当您致电 outputBytes.toString() 时,几乎可以肯定发生了一些不好的事情。

如果必须将二进制数据视为字符串,则应应用可以处理二进制数据并可靠生成可用字符串的转换。例如 base64 编码。

在您的问题中,您似乎期望未加密的文本与转换为字符串的加密字节的长度相同。没有理由证明这是真的。

您应该期望,如果您对加密字节进行加密然后解密,您将获得原始消息。但是,加密数据的大小几乎肯定不会相同。

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2015-02-05
    相关资源
    最近更新 更多