对称加密算法与非对称加密算法的异同

对称加密算法

  1. 首先对称加密算法是一个可以还原的算法,我们可以进行加密并且还原。
  2. 对称加密算法是用一个传统的一个密码进行加密和解密。
  3. 以下是在软件开发的过程中常见的加密算法。
    常见的对称加密算法
    算法密钥长度工作模式填充模式
    DES56/64ECB/CBC/PCBC/CTR/...NoPadding/PKCS5Padding/...
    AES128/192/256ECB/CBC/PCBC/CTR/...NoPadding/PKCS5Padding/PKCS7Padding/...
    IDEA128ECBPKCS5Padding/PKCS7Padding/..
  4. 密钥长度直接决定加密强度,而工作模式填充模式可以看成是对称加密算法的参数和格式选择。Java标准库提供的算法实现并不包括 所有的工作模式和所有填充模式,但是通常我们只需要挑选常用的使用就可以了。

  5. 由于DES 算法由于密钥过短,可以在短时间内被暴力破解,安全系数很低,所以我们现在普遍选择AES算法。

  • AES算法作为常用的算法,比较常见的工作模式是 ECB 和 CBC两种工作模式。

ECB模式

在ECB工作模式下,需要一个固定长度的密钥,固定的密文会生成固定的密文。以下是ECB工作模式的代码实现

public class Demo02 {
	public static void main(String[] args) throws Exception, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
		//AES加密 
		//基于一个ECB的工作模式
		String message= "tqsdyyewzdn";
		System.out.println("MESSAGE:"+message);
		//128位秘钥 = 16 bytekeys
		byte[] key = "1234567890qwerty".getBytes();
		//加密
		byte[] data = message.getBytes();
		byte[] encypted = encrypt(key, data);
		System.out.println("加密:"+Base64.getEncoder().encodeToString(encypted));
		//解密
		byte[] decrypted = decrypt(key, encypted);
		//System.out.println(Arrays.toString(decrypted));
		System.out.println("解密:"+ new String(decrypted));
	}
	//加密方法
	public static byte[] encrypt(byte[] key,byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//传入一个算法 工作模式 填充模式
		
		SecretKey keyspec = new SecretKeySpec(key, "AES");//根据key的字节内容恢复密钥对象
		
		cipher.init(Cipher.ENCRYPT_MODE, keyspec);//初始化一个秘钥,设置加密模式
		
		return cipher.doFinal(input);		
	}
	//解密
	public static byte[] decrypt(byte[] key,byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//传入一个算法 工作模式 填充模式
		
		SecretKey keyspec = new SecretKeySpec(key, "AES");//根据key的字节内容恢复密钥对象
		
		cipher.init(Cipher.DECRYPT_MODE, keyspec);//初始化一个秘钥,设置解密模式
		
		return cipher.doFinal(input);		
	}
}

CBC模式

在CBC 模式下,它需要一个随机数作为 IV 参数,这样对于同一份明文,每次生成的密文都不同。

public class Demo03 {
	public static void main(String[] args) throws Exception, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
		//AES加密 
		//基于一个CBC的工作模式
		String message= "tqsdyyewzdn";
		System.out.println("MESSAGE:"+message);
		//128位秘钥 = 16 bytekeys
		byte[] key = "1234567890qwerty1234567890qwerty".getBytes();
		//加密
		byte[] data = message.getBytes();
		byte[] encypted = encrypt(key, data);
		System.out.println("加密:"+Base64.getEncoder().encodeToString(encypted));
		//解密
		byte[] decrypted = decrypt(key, encypted);
		//System.out.println(Arrays.toString(decrypted));
		System.out.println("解密:"+ new String(decrypted));
	}
	//加密方法
	public static byte[] encrypt(byte[] key,byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//传入一个算法 工作模式 填充模式
		
		SecretKey keyspec = new SecretKeySpec(key, "AES");//根据key的字节内容恢复密钥对象
		
		//CBC模式需要生成一个16bytes的iv
		SecureRandom sr = SecureRandom.getInstanceStrong();
		//生成16字节随机数
		byte[] iv = sr.generateSeed(16);
		System.out.println(Arrays.toString(iv));
		IvParameterSpec ivps = new IvParameterSpec(iv);//随机数封装成IvParameterSpec
		
		cipher.init(Cipher.ENCRYPT_MODE, keyspec,ivps);//初始化一个秘钥,设置加密模式
		
		//加密
		byte[] data =cipher.doFinal(input);
		
		return join(iv,data);
	}
	//解密
	public static byte[] decrypt(byte[] key,byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {
		//分割input
		byte[] iv = new byte[16];
		byte[] data = new byte[input.length-16];
		System.arraycopy(input, 0, iv, 0, 16);
		System.arraycopy(input, 16, data, 0, data.length);
		//
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//传入一个算法 工作模式 填充模式
		
		SecretKey keyspec = new SecretKeySpec(key, "AES");//根据key的字节内容恢复密钥对象
		IvParameterSpec ivps = new IvParameterSpec(iv);//恢复iv
		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;
	}
}

非对称加密算法

  1. 非对称加密:加密和解密使用的不是相同的密钥,只有同一个公钥-私钥对才能正常加解密。
  2. 非对称加密的典型算法就是 RSA 算法
  3. 非对称加密的缺点:运算速度非常慢,比对称加密要慢很多
  4. 非对称加密的优点:对称加密需要协商密钥,而非对称加密可以安全地公开各自的公钥,在N个人之间通信的时候:使用非对称加密只 需要N个密钥对,每个人只管理自己的密钥对。
  5. 非对称加密的优点:而使用对称加密需要则需要N*(N-1)/2个密钥,因此每个人需要管理N-1个密钥,密钥管理难度大,而且非常容易泄漏。
  6. 以 RSA 算法为例,它的密钥有 256 / 512 / 1024 / 2048 / 4096 等不同的长度。长度越长,密码强度越大,当然计算速度也越慢。
public class Main04 {
	public static void main(String[] args) {
        // Bob和Alice:
        Person bob = new Person("Bob");
        Person alice = new Person("Alice");
        
        // 各自生成KeyPair: 公钥+私钥
        bob.generateKeyPair();
        alice.generateKeyPair();

        // 双方交换各自的PublicKey(公钥):
        // Bob根据Alice的PublicKey生成自己的本地密钥(共享公钥):
        bob.generateSecretKey(alice.publicKey.getEncoded());
        
        // Alice根据Bob的PublicKey生成自己的本地密钥(共享公钥):
        alice.generateSecretKey(bob.publicKey.getEncoded());

        // 检查双方的本地密钥是否相同:
        bob.printKeys();
        alice.printKeys();
        
        // 双方的SecretKey相同,后续通信将使用SecretKey作为密钥进行AES加解密...
    }
}

// 用户类
class Person {
    public final String name; // 姓名
    
    // 密钥
    public PublicKey publicKey; // 公钥
    private PrivateKey privateKey; // 私钥
    private byte[] secretKey; // 本地秘钥(共享密钥)

    // 构造方法
    public Person(String name) {
        this.name = name;
    }

    // 生成本地KeyPair:(公钥+私钥)
    public void generateKeyPair() {
        try {
        	// 创建DH算法的“秘钥对”生成器
            KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DH");
            kpGen.initialize(512);
            
            // 生成一个"密钥对"
            KeyPair kp = kpGen.generateKeyPair();
            this.privateKey = kp.getPrivate(); // 私钥
            this.publicKey = kp.getPublic(); // 公钥
            
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }
    
    // 按照 "对方的公钥" => 生成"共享密钥"
    public void generateSecretKey(byte[] receivedPubKeyBytes) {
        try {
            // 从byte[]恢复PublicKey:
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(receivedPubKeyBytes);
            
            // 根据DH算法获取KeyFactory
            KeyFactory kf = KeyFactory.getInstance("DH");
            // 通过KeyFactory创建公钥
            PublicKey receivedPublicKey = kf.generatePublic(keySpec);
            
            // 生成本地密钥(共享公钥)
            KeyAgreement keyAgreement = KeyAgreement.getInstance("DH");
            keyAgreement.init(this.privateKey); // 初始化"自己的PrivateKey"
            keyAgreement.doPhase(receivedPublicKey, true); // 根据"对方的PublicKey"
            
            // 生成SecretKey本地密钥(共享公钥)
            this.secretKey = keyAgreement.generateSecret();
            
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    public void printKeys() {
        System.out.printf("Name: %s\n", this.name);
        System.out.printf("Private key: %x\n", new BigInteger(1, this.privateKey.getEncoded()));
        System.out.printf("Public key: %x\n", new BigInteger(1, this.publicKey.getEncoded()));
        System.out.printf("Secret key: %x\n", new BigInteger(1, this.secretKey));
    }
}






结果为

 

 我们可以看出Private Key和Public Key不同 但是 SecretKey相同。

对称加密算法与非对称加密算法的相同

  1. 对称加密算法与非对称加密算法是、可以还原的算法,我们可以进行加密并且还原。
  2. 密钥长度直接决定加密强度

对称加密算法与非对称加密算法的不同

  1. 对称加密算法 加密和解密使用相同的秘钥,而非对称算法加密和解密采用不同的秘钥,但是通过秘钥对关联。
  2.   对称加密算法 算法公开、计算量小、速度快、加密效率高,而非对称算法更加安全但是效率低下。
  3. 对称加密算法 收、发双方所拥有的钥匙数量巨大,密钥管理成为双方的负担。非对称算法 公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。

  • 19
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值