栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Java中生成和使用两个密钥进行加密和解密

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Java中生成和使用两个密钥进行加密和解密

在更改代码之前先对其进行回答。

您正在尝试仅使用两个键而不是三个键来进行DESede。

这通常可能会奏效,但并非如您所写。问题是填充。在第二步中,您尝试使用不同于加密密钥的其他密钥解密密文,因此解密将失败超过256次中的255次,因为填充将是错误的(还因为您在其中使用base64编码)没有必要)。

如果您确实想这样做,则必须解密而无需填充和base64编码。好消息是,未编码的密文已经是块大小的倍数,因此不会阻止您使用

"DES/ECB/NoPadding"

public static void main(String[] args) {    // First I would like to create keys by giving Strings    SecretKey k1 = generateDESkey();    SecretKey k2 = generateDESkey();    // encryption    byte[] firstEncryption = desEncryption("plaintext".getBytes("UTF-8"), k1, false);    byte[] decryption = desDecryption(firstEncryption, k2, true);    byte[] secondEncryption = desEncryption(decryption, k1, true);    // decryption    byte[] firstDecryption = desDecryption(secondEncryption, k1, true);    byte[] encryption = desEncryption(firstDecryption, k2, true);    byte[] secondDecryption = desDecryption(encryption, k1, false);    System.out.println(new String(secondDecryption)); // plaintext}public static byte[] desEncryption(byte[] strToEncrypt, SecretKey desKey, boolean noPadding) {    try {        Cipher cipher = Cipher.getInstance(noPadding ? "DES/ECB/NoPadding" : "DES/ECB/PKCS5Padding");        cipher.init(Cipher.ENCRYPT_MODE, desKey);        return cipher.doFinal(strToEncrypt);    } catch (Exception ex) {        ex.printStackTrace();    }    return null;}public static byte[] desDecryption(byte[] strToDecrypt, SecretKey desKey, boolean noPadding) {    try {        Cipher cipher = Cipher.getInstance(noPadding ? "DES/ECB/NoPadding" : "DES/ECB/PKCS5Padding");        cipher.init(Cipher.DECRYPT_MODE, desKey);        return cipher.doFinal(strToDecrypt);    } catch (Exception ex) {        ex.printStackTrace();    }    return null;}

当以这种方式构造通用密钥时,这实际上是具有两个密钥的DESede的等效实现:

SecretKey k1 = generateDESkey();SecretKey k2 = generateDESkey();byte[] edeKeyBytes = new byte[24];System.arraycopy(k1.getEnpred(), 0, edeKeyBytes, 0, 8);System.arraycopy(k2.getEnpred(), 0, edeKeyBytes, 8, 8);System.arraycopy(k1.getEnpred(), 0, edeKeyBytes, 16, 8);edeKey = new SecretKeySpec(edeKeyBytes, "DESede");Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, edeKey);System.out.println(base64.enpre(cipher.doFinal("plaintext".getBytes("UTF-8"))));

DESede使用三个密钥,我们将其称为k1,k2和k3。所有这些都串联到一个字节数组中。在您的情况下,第二次使用k1代替k3。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/574327.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号