1、Des symmetric encryption
Data Encryption Standard is a symmetric-key algorithm for the encrypting the data. It comes under block cipher algorithm which follows Feistel structure. Here is the block diagram of Data Encryption Standard.
image.png
加密原理
编辑 DES 使用一个 56 位的密钥以及附加的 8 位奇偶校验位,产生最大 64 位的分组大小。这是一个迭代的分组密码,使用称为 Feistel 的技术,其中将加密的文本块分成两半。使用子密钥对其中一半应用循环功能,然后将输出与另一半进行“异或”运算;接着交换这两半,这一过程会继续下去,但最后一个循环不交换。DES 使用 16 个循环,使用异或,置换,代换,移位操作四种基本运算。
2、具体实现与解释如下:
package com.company;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class DESUtil {
/*
* 生成密钥
*/
public static byte[] initKey() throws Exception{
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
keyGen.init(56);
SecretKey secretKey = keyGen.generateKey();
return secretKey.getEncoded();
}
/*
* DES 加密
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherBytes = cipher.doFinal(data);
return cipherBytes;
}
/*
* DES 解密
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainBytes = cipher.doFinal(data);
return plainBytes;
}
//Test
public static void main(String[] args) throws Exception {
byte[] desKey = DESUtil.initKey();
System.out.println("DES KEY : "+new String(desKey,"UTF-8"));
String DATA = "Rashidin🦅";
byte[] desResult = encrypt(DATA.getBytes() , desKey);
System.out.println(DATA + ">>>DES 加密结果>>>" + new String(desResult,"UTF-8"));
byte[] desPlain = DESUtil.decrypt(desResult, desKey);
System.out.println(DATA + ">>>DES 解密结果>>>" + new String(desPlain));
}
}
运行结果为:
image.png