加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java:使用CTR模式的AES加密;无法解密

发布时间:2020-12-15 08:49:39 所属栏目:Java 来源:网络整理
导读:我正在使用以下代码,但它没有正确解密文本,我得到的是输出 加密:%?No2F?¢?SHo??“?? 明文:你好×amorigin?l public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // Dernier exemple CTR mode // Clé 16
我正在使用以下代码,但它没有正确解密文本,我得到的是输出

加密:%?No2F?¢?SHo??“??

明文:你好×amorigin?l

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    // Dernier exemple CTR mode
    // Clé 16 bits
    byte[] keyBytes = new byte[] { (byte) 0x36,(byte) 0xf1,(byte) 0x83,(byte) 0x57,(byte) 0xbe,(byte) 0x4d,(byte) 0xbd,(byte) 0x77,(byte) 0xf0,(byte) 0x50,(byte) 0x51,(byte) 0x5c,0x73,(byte) 0xfc,(byte) 0xf9,(byte) 0xf2 };
    // IV 16 bits (préfixe du cipherText)
    byte[] ivBytes = new byte[] { (byte) 0x69,(byte) 0xdd,(byte) 0xa8,(byte) 0x45,(byte) 0x7d,(byte) 0xd4,(byte) 0x25,(byte) 0x4b,(byte) 0xf3,(byte) 0x53,(byte) 0xb7,(byte) 0x73,(byte) 0x30,(byte) 0x4e,(byte) 0xec };

    // Initialisation
    SecretKeySpec key = new SecretKeySpec(keyBytes,"AES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

    // Mode
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

    String originalText = "hello i am original";
    // ///////////////////////////////ENCRYPTING
    cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
    byte[] ciphered = cipher.doFinal(originalText.getBytes());
    String cipherText = new String(ciphered,"UTF-8");
    System.out.println("ciphered: " + cipherText);
    // ///////////////////////////////DECRYPTING
    cipher = Cipher.getInstance("AES/CTR/NoPadding");

    cipher.**init(Cipher.DECRYPT_MODE**,ivSpec);
    byte[] plain = **cipher.doFinal(ciphered);**
    originalText = new String(plain,"UTF-8");
    System.out.println("plaintext: " + originalText);
}

我无法弄清楚我做错了什么.非常感谢任何帮助.
也是这种加密一些数据的正确方法,这次我试图加密4byte城市密码.
预先感谢

////

我做了那些改变,它工作得很好,但如果我通过了,问题是什么
?cipher.init()函数中的cipherText.getByte().喜欢

byte[] plain = cipher.doFinal(cipherText.getByte("UTF-8"));

‘谢谢你的帮助.

解决方法

对于解密,您需要在DECRYPT_MODE中初始化密码.而且byte []到String的转换也不正确(参见其他答案).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读