1.密码算法分类
- 消息编程,Base64:为了适应一些系统不支持非ASCII的数据,所以需要将数据转换成ASCII格式,Base64就是一种转换方式,Base64是将3个8bit的字节转换成为4个6bit的字节,转换后的字节高位补0,如aaaaaaaabbbbbbbbcccccccc会被转换成00aaaaaa,00aabbbb,00bbbbcc,00cccccc,接受端进行反向解码即可。
- 消息摘要:MD类、SHA类、MAC(消息验证码,在MD类与SHA类上增加了密钥的支持)
- 对称密码:DES、3DES、AES(对称密码的标准(最新),增加了密钥的长度)
- 非对称密码:RSA、DH密钥交换
- 数字签名:RSASignature(基于RSA)、DSASignature(基于DSA)
2.Base64 demo
package com.xiayu.demo;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
public class BaseDemo {
public static void main(String[] args) throws IOException {
//此处仅仅为演示demo,这样写违反类单一职责原则,可以将编解码方法单独放置一个类中。
BASE64Encoder encoder = new BASE64Encoder();
BASE64Decoder decoder = new BASE64Decoder();
String data = "zhengzhou";
String encodeData = encoder.encodeBuffer(data.getBytes());
byte[] decodeData = decoder.decodeBuffer(encodeData);
System.out.println(new String(decodeData));
}
}
结果
3.消息摘要
-
MD5
package com.xiayu.demo; import org.springframework.util.DigestUtils; //使用spring的DigestUtils工具 public class Md5Util { public static String encodeMd5Hex(String data){ if (data != null && data.length() > 0){ String encodedData = DigestUtils.md5DigestAsHex(data.getBytes()); return encodedData; } return null; } public static boolean verify(String data,String encodedData){ if (data != null && data.length() > 0 && encodedData != null && encodedData.length() > 0){ return encodedData.equals(DigestUtils.md5Digest(data.getBytes())); } return false; } }
-
SHA256
------------------java自带实现方式--------------- package com.xiayu.demo; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class SHA256 { public static String getSHA256StrJava(String data){ MessageDigest messageDigest; String encodeStr = ""; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(data.getBytes("UTF-8")); encodeStr = byte2Hex(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodeStr; } private static String byte2Hex(byte[] bytes){ StringBuffer stringBuffer = new StringBuffer(); String temp = null; for (int i=0;i<bytes.length;i++){ temp = Integer.toHexString(bytes[i] & 0xFF); if (temp.length()==1){ stringBuffer.append("0"); } stringBuffer.append(temp); } return stringBuffer.toString(); } } ------------------java自带实现方式---------------
apache工具类
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> public static String getSHA256Data(String data){ if (data == null || data.length() == 0){ return null; } MessageDigest messageDigest; String encdeStr; try { messageDigest = MessageDigest.getInstance("SHA-256"); byte[] hash = messageDigest.digest(data.getBytes("UTF-8")); encdeStr = Hex.encodeHexString(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encdeStr; }
4.对称加密
AES加解密工具类
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class AESUtil { public static String encrypt(String key,String content){ try { KeyGenerator keygen=KeyGenerator.getInstance("AES"); keygen.init(128, new SecureRandom(key.getBytes())); SecretKey original_key=keygen.generateKey(); byte [] raw=original_key.getEncoded(); SecretKey secretKey=new SecretKeySpec(raw, "AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte [] contentBytes=content.getBytes("utf-8"); byte [] encryptedByte=cipher.doFinal(contentBytes); String encryptedString=new String(new BASE64Encoder().encode(encryptedByte)); return encryptedString; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String decrypted(String key,String content){ try { KeyGenerator keygen=KeyGenerator.getInstance("AES"); keygen.init(128, new SecureRandom(key.getBytes())); SecretKey original_key=keygen.generateKey(); byte [] raw=original_key.getEncoded(); SecretKey secretKey=new SecretKeySpec(raw, "AES"); Cipher cipher=Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte [] byte_content= new BASE64Decoder().decodeBuffer(content); byte [] byte_decode=cipher.doFinal(byte_content); String AES_decode=new String(byte_decode,"utf-8"); return AES_decode; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String content = "zzu"; String key = "345234523423452345"; System.out.println("key:" +key+" content:" + content); String encryptedResult = AESUtil.encrypt(key,content); System.out.println("encryptedResult:" + encryptedResult); String decryptedResult = AESUtil.decrypted(key, encryptedResult); System.out.println("decryptedResult:" + decryptedResult); } }
5.非对称加密
RSA加解密demo,参考
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; public class RSAUtil { private final static String KEY_RSA = "RSA"; private final static String KEY_RSA_SIGNATURE = "MD5withRSA"; private final static String KEY_RSA_PUBLICKEY = "RSAPublicKey"; private final static String KEY_RSA_PRIVATEKEY = "RSAPrivateKey"; public static Map<String, Object> init() { Map<String, Object> map = null; try { //生成秘钥对 KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA); generator.initialize(1024); KeyPair keyPair = generator.generateKeyPair(); // 获取公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 获取私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 将密钥封装为map map = new HashMap<>(); map.put(KEY_RSA_PUBLICKEY, publicKey); map.put(KEY_RSA_PRIVATEKEY, privateKey); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return map; } public static String sign(byte[] data, String privateKey) { String str = ""; try { // 解密由base64编码的私钥 byte[] bytes = decryptBase64(privateKey); // 构造PKCS8EncodedKeySpec对象 PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes); // 指定的加密算法 KeyFactory factory = KeyFactory.getInstance(KEY_RSA); // 取私钥对象 PrivateKey key = factory.generatePrivate(pkcs); // 用私钥对信息生成数字签名 Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE); signature.initSign(key); signature.update(data); str = encryptBase64(signature.sign()); } catch (Exception e) { e.printStackTrace(); } return str; } public static boolean verify(byte[] data, String publicKey, String sign) { boolean flag = false; try { // 解密由base64编码的公钥 byte[] bytes = decryptBase64(publicKey); // 构造X509EncodedKeySpec对象 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); // 指定的加密算法 KeyFactory factory = KeyFactory.getInstance(KEY_RSA); // 取公钥对象 PublicKey key = factory.generatePublic(keySpec); // 用公钥验证数字签名 Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE); signature.initVerify(key); signature.update(data); flag = signature.verify(decryptBase64(sign)); } catch (Exception e) { e.printStackTrace(); } return flag; } public static byte[] decryptByPrivateKey(byte[] data, String key) { byte[] result = null; try { // 对私钥解密 byte[] bytes = decryptBase64(key); // 取得私钥 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(KEY_RSA); PrivateKey privateKey = factory.generatePrivate(keySpec); // 对数据解密 Cipher cipher = Cipher.getInstance(factory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); result = cipher.doFinal(data); } catch (Exception e) { e.printStackTrace(); } return result; } public static byte[] decryptByPublicKey(byte[] data, String key) { byte[] result = null; try { // 对公钥解密 byte[] bytes = decryptBase64(key); // 取得公钥 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(KEY_RSA); PublicKey publicKey = factory.generatePublic(keySpec); // 对数据解密 Cipher cipher = Cipher.getInstance(factory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); result = cipher.doFinal(data); } catch (Exception e) { e.printStackTrace(); } return result; } public static byte[] encryptByPublicKey(byte[] data, String key) { byte[] result = null; try { byte[] bytes = decryptBase64(key); // 取得公钥 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(KEY_RSA); PublicKey publicKey = factory.generatePublic(keySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(factory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); result = cipher.doFinal(data); } catch (Exception e) { e.printStackTrace(); } return result; } public static byte[] encryptByPrivateKey(byte[] data, String key) { byte[] result = null; try { byte[] bytes = decryptBase64(key); // 取得私钥 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(KEY_RSA); PrivateKey privateKey = factory.generatePrivate(keySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(factory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateKey); result = cipher.doFinal(data); } catch (Exception e) { e.printStackTrace(); } return result; } public static String getPublicKey(Map<String, Object> map) { String str = ""; try { Key key = (Key) map.get(KEY_RSA_PUBLICKEY); str = encryptBase64(key.getEncoded()); } catch (Exception e) { e.printStackTrace(); } return str; } public static String getPrivateKey(Map<String, Object> map) { String str = ""; try { Key key = (Key) map.get(KEY_RSA_PRIVATEKEY); str = encryptBase64(key.getEncoded()); } catch (Exception e) { e.printStackTrace(); } return str; } public static byte[] decryptBase64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } public static String encryptBase64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } public static void main(String[] args) { String privateKey = ""; String publicKey = ""; // 生成公钥私钥 Map<String, Object> map = init(); publicKey = getPublicKey(map); privateKey = getPrivateKey(map); System.out.println("公钥: " + publicKey); System.out.println("私钥:" + privateKey); System.out.println("公钥加密--------私钥解密"); String word = "郑州郑州郑州"; byte[] encWord = encryptByPublicKey(word.getBytes(), publicKey); String decWord = new String(decryptByPrivateKey(encWord, privateKey)); System.out.println("加密前: " + word + "\n\r" + "解密后: " + decWord); System.out.println("私钥加密--------公钥解密"); String english = "Hello, World!"; byte[] encEnglish = encryptByPrivateKey(english.getBytes(), privateKey); String decEnglish = new String(decryptByPublicKey(encEnglish, publicKey)); System.out.println("加密前: " + english + "\n\r" + "解密后: " + decEnglish); System.out.println("私钥签名——公钥验证签名"); // 产生签名 String sign = sign(encEnglish, privateKey); System.out.println("签名:" + sign); // 验证签名 boolean status = verify(encEnglish, publicKey, sign); System.out.println("状态:" + status); } }
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。