当前位置:网站首页>Comparison between symmetric encryption and asymmetric encryption
Comparison between symmetric encryption and asymmetric encryption
2022-07-22 17:24:00 【I like iced black tea】
Symmetric encryption algorithm
Algorithm | Key length | Working mode |
DES( Version is too old ) | 56/64 | ECB/CBC/PCBC/CTR/... |
AES | 128/192/256 | ECB/CBC/PCBC/CTR/... |
IDEA | 128 | ECB |
- Set algorithm / Working mode /ECB/ Fill mode
- according to key Byte content of , Restore the secret key object
- Initialize key : Set encryption mode
- Encrypt according to the original content bytes : Returns an array of bytes
- Set algorithm / Working mode /ECB/ Fill mode
- according to key Byte content of , Restore the secret key object
- Initialize key : Set decryption mode
- Decrypt according to the encrypted content bytes :
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
//ECB Pattern
public class Test {
public static void main(String[] args) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
// original text
String message = "Hello";
//128 A key = 16 bytes key:
byte[] key = "1234567890abcdef".getBytes();
// encryption
byte[] data = message.getBytes();
byte[] encrypted = encrypt(key, data);
System.out.println("Encrypted( Encrypted content ):" +
Base64.getEncoder().encodeToString(encrypted));
// Decrypt
byte[] decrypted = decrypt(key, encrypted);
System.out.println("Decrypted( Decrypt content ):"+ new String(decrypted));
}
// encryption :
public static byte[] encrypt(byte[] key,byte[] input) throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
// Create password object : Need to pass in the algorithm / Working mode / Fill mode
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// according to key Byte content of ,“ recovery ” Secret key object
SecretKey keySpec = new SecretKeySpec(key,"AES");
// Initialization key : Set encryption mode ENCRYPT_MOD
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
// According to the original content ( byte ) To decrypt
return cipher.doFinal(input);
}
// Decrypt
public static byte[] decrypt(byte[] key,byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
// Create password object : Need to pass in the algorithm / Working mode / Fill mode
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// according to key Byte content of ,“ recovery ” Secret key object
SecretKey keySpec = new SecretKeySpec(key,"AES");
// Initialization key : Set encryption mode DECRYPT_MOD
cipher.init(Cipher.DECRYPT_MODE, keySpec);
// According to the original content ( byte ) To decrypt
return cipher.doFinal(input);
}
}
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Test {
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
// original text
String message = "Hello";
//256 A key =32 bytes key:
byte[] key = "1234567890abcdef1234567890abcdef".getBytes();
// encryption
byte[] data = message.getBytes();
byte[] encrypted = encrypt(key, data);
System.out.println("Encrypted( Encrypted content ):" +
Base64.getEncoder().encodeToString(encrypted));
// Decrypt
byte[] decrypted = decrypt(key, encrypted);
System.out.println("Decrypted( Decrypt content ):"+ new String(decrypted));
}
// encryption
public static byte[] encrypt(byte[] key,byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
// Set algorithm / Working mode CBC/ fill
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Recovery key object
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
//CBC The pattern needs to generate a 16bytes Of initialization vector
SecureRandom sr = SecureRandom.getInstanceStrong();
byte[] iv = sr.generateSeed(16);// Generate 16 A random number of bytes
System.out.println(Arrays.toString(iv));
IvParameterSpec ivps = new IvParameterSpec(iv);// Random numbers are encapsulated into IvParameterSpec
// Initialization key : Operation mode 、 Secret key 、IV Parameters
cipher.init(Cipher.ENCRYPT_MODE, keySpec,ivps);
// encryption
byte[] data = cipher.doFinal(input);
//IV There is no need to keep it secret , hold IV Return with ciphertext
return join(iv,data);
}
// Decrypt
public static byte[] decrypt(byte[] key,byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
// hold input Divided into IV And ciphertext
byte[] iv = new byte[16];
byte[] data = new byte[input.length-16];
System.arraycopy(input, 0, iv, 0, 16);//IV
System.arraycopy(input, 16, data, 0, data.length);// Ciphertext
System.out.println(Arrays.toString(iv));
// Decrypt
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// Password object
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");// Recovery key
IvParameterSpec ivps = new IvParameterSpec(iv);// recovery IV
// Initialization key : Operation mode 、 Secret key 、IV Parameters
cipher.init(Cipher.DECRYPT_MODE, keySpec,ivps);
return cipher.doFinal(data);
}
public static byte[] join(byte[] bs1,byte[] bs2) {
byte[] r = new byte[bs1.length+bs2.length];
System.arraycopy(bs1, 0, r, 0, bs1.length);
System.arraycopy(bs2, 0, r, bs1.length, bs2.length);
return r;
}
}
Asymmetric encryption algorithm
- First, a key pair must be generated
- Use public key encryption
- Decrypt with private key
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
// RSA
public class Test {
public static void main(String[] args) throws Exception {
// Plaintext :
byte[] plain = "Hello, encrypt use RSA".getBytes("UTF-8");
// Create public key / Private key pair :
Human alice = new Human("Alice");
// use Alice Public key encryption :
// obtain Alice The public key , And the output
byte[] pk = alice.getPublicKey();
System.out.println(String.format("public key( Public key ): %x", new BigInteger(1, pk)));
// Use public key encryption
byte[] encrypted = alice.encrypt(plain);
System.out.println(String.format("encrypted: %x", new BigInteger(1, encrypted)));
// use Alice Private key decryption of :
// obtain Alice The private key , And the output
byte[] sk = alice.getPrivateKey();
System.out.println(String.format("private key: %x", new BigInteger(1, sk)));
// Decrypt with private key
byte[] decrypted = alice.decrypt(encrypted);
System.out.println(new String(decrypted, "UTF-8"));
}
}
// User class
class Human {
// full name
String name;
// Private key :
PrivateKey sk;
// Public key :
PublicKey pk;
// Construction method
public Human(String name) throws GeneralSecurityException {
// Initialize name
this.name = name;
// Generate public key / Private key pair :
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
this.sk = kp.getPrivate();
this.pk = kp.getPublic();
}
// Export the private key as bytes
public byte[] getPrivateKey() {
return this.sk.getEncoded();
}
// Export the public key as bytes
public byte[] getPublicKey() {
return this.pk.getEncoded();
}
// Encrypt with a public key :
public byte[] encrypt(byte[] message) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, this.pk); // Initialize with public key
return cipher.doFinal(message);
}
// Decrypt with private key :
public byte[] decrypt(byte[] input) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, this.sk); // Initialize with the private key
return cipher.doFinal(input);
}
}
The difference between symmetric encryption and asymmetric encryption
1、 The secret key used for encryption and decryption in symmetric encryption is the same ; Two keys are used in asymmetric encryption , Generally, public key is used for encryption , The private key is decrypted .
2、 The speed of symmetric encryption and decryption is relatively fast , Asymmetric encryption and decryption take a long time 、 Relatively slow .
3、 The security of symmetric encryption is relatively low , Asymmetric encryption has high security .
边栏推荐
猜你喜欢
Solidworks基础特征你了解多少?| 拉伸特征的4种方法
UE4 use of vegetation tools
【LeetCode】814. 二叉树剪枝
The three formats of the log "binlog" in MySQL are so interesting
1312. 让字符串成为回文串的最少插入次数
[C language interesting experiment]
MVC模式和三层架构
《PyTorch深度学习实践》-B站 刘二大人-day1
MATLAB函数:filtfilt——零相位数字滤波
UE4 lifts the elevator by pressing the key
随机推荐
Xshell Plus6下载及安装使用的方法
【外部排序】归并思想完成外部排序
【外部排序】快排思想完成外部排序
Server network performance tuning cases
【矩阵乘法】外部矩阵乘法
mysql约束之_唯一约束
服务器网络性能调优工具
Lepton 无损压缩原理及性能分析
Win11开机只有鼠标显示怎么办?
[machine learning] how pytorch loads custom datasets and divides them
2022年暑假ACM热身练习3(部分题目总结)
Recommendation of selected topics for completed topics of Electronic Information Engineering
DOF depth of field Foundation
UE4 keyboard keys realize door opening and closing
一种跳板机的实现思路
MVC模式和三层架构
The three formats of the log "binlog" in MySQL are so interesting
How to solve the problem of uncontrollable win11 flashing white screen?
JS的DOM操作——事件链(冒泡目标捕获)
LCD笔记(3)写出LCD基本驱动框架