加密入门-从凯撒密码说起

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BayMax_0X0001/article/details/82967958
package PostPager;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.util.Base64Utils;

public class Demo01 {

	public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		String clearText = "helloWord";
		// 要求秘钥8个字节
		String originKey = "15425845";
		String cipherText =  desencript(clearText,originKey);
		System.out.println(cipherText);
	}

	private static String desencript(String clearText, String originKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		// 获取加密算法工具
		Cipher cipher = Cipher.getInstance("DES");
		// 对加密工具类对象进行初始化
		SecretKeySpec secretKeySpec = new SecretKeySpec(originKey.getBytes(), "DES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		// 用加密工具类对象对明文进行加密
		byte[] doFinal = cipher.doFinal(clearText.getBytes());
		return Base64Utils.encodeToString(doFinal);
	}

	// 解密方法和加密相似,先用Base64解码,再用相同的密匙解密就可以了
}
package PostPager;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.util.Base64Utils;

public class Demo02 {

	public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		String clearText = "helloWord";
		// DES要求秘钥8个字节   AES一般要求密匙16个字节
		String originKey = "1542584545125895";
		String cipherText =  AESencript(clearText,originKey);
		System.out.println(cipherText);
	}

	private static String AESencript(String clearText, String originKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		// 获取加密算法工具
		Cipher cipher = Cipher.getInstance("AES");
		// 对加密工具类对象进行初始化
		SecretKeySpec secretKeySpec = new SecretKeySpec(originKey.getBytes(), "AES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		// 用加密工具类对象对明文进行加密
		byte[] doFinal = cipher.doFinal(clearText.getBytes());
		return Base64Utils.encodeToString(doFinal);
	}

	// 解密方法和加密相似,先用Base64解码,再用相同的密匙解密就可以了
}

猜你喜欢

转载自blog.csdn.net/BayMax_0X0001/article/details/82967958