java 使用密钥加密_在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.getEncoded(), 0, edeKeyBytes, 0, 8);

System.arraycopy(k2.getEncoded(), 0, edeKeyBytes, 8, 8);

System.arraycopy(k1.getEncoded(), 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.encode(cipher.doFinal("plaintext".getBytes("UTF-8"))));

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

2020-11-19

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值