Java加密总结:常见哈希算法总结、对称式加密与非对称式加密的对比

一、常见的哈希算法的总结


1.哈希碰撞

(输入两个不同的值得到相同的结果),碰是不能避免的,因为输出的字节长度是固定的,String的hashCode90输出是4字节整数,是有限的。

"AaAaAa".hashCode(); // 0x7460e8c0
"BBAaBB".hashCode(); // 0x7460e8c0

2.常用的哈希算法

1MD5算法

package com.xiaojia;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Test {
	public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		//创建一个MessageDigest实例
		MessageDigest ch = MessageDigest.getInstance("MD5");
		//反复调用update输出数据
		ch.update("cui".getBytes("UTF-8"));
		ch.update("hua".getBytes("UTF-8"));
		
		byte[] results = ch.digest();
		StringBuilder xh = new StringBuilder();
		for(byte bite : results) {
			xh.append(String.format("%02x", bite));
		}
		System.out.println(xh.toString());
		
		
	}

}

1.1MD5算法(加密后的算法转化成字符串)

String password = "123321cuihuabuyaochoule";
try{
    MessageDigest message = MessageDigest.getInstance("MD5");
    message.update(password.getBytes());
    byte[] resultByteArray = message.digest();
    StringBuilder result = new StringBUilder();
    for(byte bite : resultByteArray){
        result.append(String.format("%20x",bite));
    }
    System.out.println(result);
     System.out.println(result.length());

} catch (NoSuchAlgorithmException e) {
			
			e.printStackTrace();
		}

2SHA-1算法

String password = "123321cuihuabuyaochoule";
String stld = UUID.randUUID().toString().substring(0,6);
System.out.println(stld);

try{
    MessageDigest message = MessageDigest.getInstance("SHA-1");
    message.update(password.getByte());
    message.update(stld.getByte());
    byte[] resultByteArray = message.digest();
    StringBuilder result = new StringBuilder();
    for(byte bite : resultByteArray){
        result.append(String.format("%02x",bite));
    }
    System.out.println(result1);
}catch (NoSuchAlgorithmException e) {
			
			e.printStackTrace();
		}

3.HmacMD5算法

String password = "cuihua";

try{
    KeyGenerator keygen = KeyGenerator.getInstance("HmacMD5");
    SecretKey key = keygen.generateKey();
    byte[] keyByteArray = key.getEncoded();
    StringBUilder KeyStr = new StringBuilder();
    for(byte bite : keyByteArray){
        KeyStr.append(String.format("%02x",bite));
    
    Mac mac = Mac.getInstance("HmacMD5");
    mac.init(key);
    mac.update(password.getBytes());
    byte[] resultByteArray = mac.doFinal();
    StringBuilder resultStr = new BuilderString();
    for(byte b : resultByteArray){
        resultStr.append(String.format("%02x",b));
    }catch (NoSuchAlgorithmException e) {
			
			e.printStackTrace();
		}
    













}

总结

哈希算法可以用于验证完整性,具有防篡改功能

常用的哈希算法有MD5,SHA-1等。

2.对称加密算法:

对称加密算法就是传统的用一个密码进行加密和解密,常用的有WinZIP和WinRAR对压缩包的加密和解密。

在软件开发中,常用的堆成加密算法有(密钥的长度直接决定加密强度):

 使用AEC加密(比较常见的工作模式是ECB和CBC,密钥长度由算法设计决定,AES的密钥长度是128/192/256位,使用堆成加密算法需要指定算法名称、工作模式、填充模式)

ECB模式

package com.xiao;

import java.security.GeneralSecurityException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Morningtwozero1 {
	public static void main(String[] args) throws Exception, GeneralSecurityException  {
		//原文
		String message = "Sey baibai";
		System.out.println("Message:" + message);
		
		//128位密钥 = 16 bytes Key
		byte[] key = "1234567980abcdrf".getBytes();
		
		//加密
		byte[] data = message.getBytes();
		byte[] encrypted = encrypt(key,data);
		System.out.println("Encrypted(加密):" + Base64.getEncoder().
				encodeToString(encrypted));
		
		//解密
		byte[] decrypted = decrypt(key, encrypted);
		System.out.println("Decryted:" + new String(decrypted));
		
		
		
		
	}
	
	//加密
	public static byte[] encrypt(byte[] key , byte[] input) throws GeneralSecurityException, NoSuchPaddingException   {
		//创建密码对象,需要传入算法/工作模式/填充模式
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		
		//根据key的字节内容,“恢复”密钥对象
		SecretKey keySpec = new SecretKeySpec(key, "AES");
		
		//初始化密钥:设置加密模式ENCRYPT_MODE
		cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		
		//根据原始内容(字节)进行加密
		return cipher.doFinal(input);
		
	}
	
	//解密
	public static byte[] decrypt(byte[] key,byte[] input) throws GeneralSecurityException, NoSuchPaddingException   {
		//创建密码对象,需要传入算法/工作模式./填充模式
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		
		//根据key的字节内容,“恢复”密钥对象
		SecretKey keySpec = new SecretKeySpec(key,"AES");
		
		//初始化密钥,设置解密模式
		cipher.init(Cipher.DECRYPT_MODE, keySpec);
		
		//根据原始内容(字节),进行解密
		return cipher.doFinal(input);
	
	}
	
}

步骤:1:根据算法名称/工作模式/填充模式获取Cipher实例

           2:根据算法名称初始化一个SecretKey实例,密钥必须是指定长度

           3:使用SerectKey初始化Cipher实例,并设置加密或解密模式

            4:传入明文或密文,获得密文或明文

CBC模式

package com.xiao;

import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
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.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Morningtwozero2 {
	public static void main(String[] args) throws GeneralSecurityException, GeneralSecurityException {
		String message = "dawd";
		System.out.println("Message(原始信息) " + message);
		
		byte[] key  = "1234567980abcdrf1234567980abcdrf".getBytes();
		
		byte[] data = message.getBytes();
		byte[] encryted = encrypt(key,data);
		System.out.println("Encrypted" + Base64.getEncoder().encodeToString(encryted));
		//解密
		byte[] decrypted = decrypt(key,encryted);
		System.out.println("Decrypted" + new String(decrypted));
	}
	
	public static byte[] encrypt(byte[] key,byte[] input) throws GeneralSecurityException, InvalidAlgorithmParameterException {
		//设置算法/工作模式CBC/填充
		Cipher cipher  = Cipher.getInstance("AES/CBC/PKCS5Padding");
		
		//恢复密钥对象
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		
		//CBC模式需要生成一个16 bytes的initialization vector;
		SecureRandom sr = SecureRandom.getInstanceStrong();
		byte[] iv = sr.generateSeed(16);//生成16个字节的随机数
		System.out.println(Arrays.toString(iv));
		IvParameterSpec ivps = new IvParameterSpec(iv);//随机数封装成IvParameterSpec
		
		//初始化密钥:操作模式、密钥、IV参数
		cipher.init(Cipher.ENCRYPT_MODE,keySpec, ivps);
		
		//加密
		byte[] data = cipher.doFinal(input);
		
		//IV不要用保密,把IBV和密文一起返回
		return join(iv,data);
		
	}
	//解密
	public static byte[] decrypt(byte[] key,byte[] input) throws GeneralSecurityException, BadPaddingException {
		//把input分割成OIV和密文
		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);//密文
		System.out.println(Arrays.toString(iv));
		
		//解密
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
		IvParameterSpec ivps = new IvParameterSpec(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;
		
	}

}

在CBC模式下,需要一个随机生成的16字节IV参数,必须使用SecureRandom生成,

3.非对称加密算法

加密和解密使用的不是相同的密钥,只有同一个公钥-私钥对才能正常加解密

RSA算法它的密钥有256/512/1024/2048/4096等不同的长度。长度越长,密钥强度越大,计算速度也越慢。

RSA算法

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 Main {
	public static void main(String[] args) throws Exception {
		// 明文:
		byte[] plain = "Hello, encrypt use RSA".getBytes("UTF-8");

		// 创建公钥/私钥对:
		Human alice = new Human("Alice");

		// 用Alice的公钥加密:
		// 获取Alice的公钥,并输出
		byte[] pk = alice.getPublicKey();
		System.out.println(String.format("public key(公钥): %x", new BigInteger(1, pk)));

		// 使用公钥加密
		byte[] encrypted = alice.encrypt(plain);
		System.out.println(String.format("encrypted(加密): %x", new BigInteger(1, encrypted)));

		// 用Alice的私钥解密:
		// 获取Alice的私钥,并输出
		byte[] sk = alice.getPrivateKey();
		System.out.println(String.format("private key(私钥): %x", new BigInteger(1, sk)));

		// 使用私钥解密
		byte[] decrypted = alice.decrypt(encrypted);
		System.out.println("decrypted(解密): " + new String(decrypted, "UTF-8"));
	}
}

// 用户类
class Human {
	// 姓名
	String name;

	// 私钥:
	PrivateKey sk;

	// 公钥:
	PublicKey pk;

	// 构造方法
	public Human(String name) throws GeneralSecurityException {
		// 初始化姓名
		this.name = name;

		// 生成公钥/私钥对:
		KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
		kpGen.initialize(1024);
		KeyPair kp = kpGen.generateKeyPair();

		this.sk = kp.getPrivate();
		this.pk = kp.getPublic();
	}

	// 把私钥导出为字节
	public byte[] getPrivateKey() {
		return this.sk.getEncoded();
	}

	// 把公钥导出为字节
	public byte[] getPublicKey() {
		return this.pk.getEncoded();
	}

	// 用公钥加密:
	public byte[] encrypt(byte[] message) throws GeneralSecurityException {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, this.pk); // 使用公钥进行初始化
		return cipher.doFinal(message);
	}

	// 用私钥解密:
	public byte[] decrypt(byte[] input) throws GeneralSecurityException {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, this.sk); // 使用私钥进行初始化
		return cipher.doFinal(input);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值