一、MD5加密
密文形式:
5eb63bbbe01eeed093cb22bb8f5acdc3
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static String stringToMD5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有这个md5算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
public static void main(String[] args) {
System.out.println(stringToMD5("hello world"));
}
}
二、RSA加解密(公加私解,私加公解)
密文形式:
W1WTmVo870wB9t6/kGxTV4b2wuI7iHGLNDP+24SyD45==
package com.bytedance.frameworks.core.encrypt;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSA {
public static String RSAEncryptByPublickey(String str, String publicKey) throws Exception {
/* RSA通过公钥加密 */
//base64编码的公钥
byte[] decoded = Base64.decode(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encode(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
public static String RSAEncryptByPrivatekey(String content,String private_key) {
/* RSA通过私钥加密 */
String charset = "utf-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(private_key));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String RSADecryptByPublicKey(String str, String publicKey) throws Exception {
/* RSA通过公钥解密 */
byte[] inputByte = Base64.decode(str);
//base64编码的私钥
byte[] decoded = Base64.decode(publicKey);
PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, pubKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
public static String RSADecryptByPrivateKey(String data, String privateKey) throws Exception {
/* RSA通过私钥解密 */
byte[] inputByte = Base64.decode(data);
//base64编码的私钥
byte[] decoded = Base64.decode(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
String str1 = outStr.substring(0,32);
String hex = base64Tohex(str1);
String Des_key = hex.substring(0,16);
return Des_key;
}
public static String byteToHex(byte b)
{
String hexString = Integer.toHexString(b & 0xFF);
//由于十六进制是由0~9、A~F来表示1~16,所以如果Byte转换成Hex后如果是<16,就会是一个字符(比如A=10),通常是使用两个字符来表示16进制位的,
//假如一个字符的话,遇到字符串11,这到底是1个字节,还是1和1两个字节,容易混淆,如果是补0,那么1和1补充后就是0101,11就表示纯粹的11
if (hexString.length() < 2)
{
hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
}
return hexString.toUpperCase();
}
public static String bytesToHex(byte[] bytes)
{
StringBuffer sb = new StringBuffer();
if (bytes != null && bytes.length > 0)
{
for (int i = 0; i < bytes.length; i++) {
String hex = byteToHex(bytes[i]);
sb.append(hex);
}
}
return sb.toString();
}
public static String base64Tohex(String bstxt){
byte[] bs = Base64.decode(bstxt);
String hex = bytesToHex(bs);
return hex.toLowerCase();
}
public static void main(String[] args) {
}
}
三、RSA私钥加密(签名)
package APP;
import sun.misc.BASE64Decoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class RSA {
public static String encryptByPrivateKey(String content,String privateKey) throws Exception {
// BC模式
java.security.Security.addProvider(
new org.bouncycastle.jce.provider.BouncyCastleProvider()
);
//解密私钥
byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(privateKey);
// byte[] keyBytes = privateKey.getBytes();
//构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
//指定加密算法
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//取私钥匙对象
PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//用私钥对信息生成数字签名
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initSign(privateKey2);
signature.update(content.getBytes());
return Base64.getEncoder().encodeToString(signature.sign());
}
public static void main(String[] args) throws Exception {
String privateKey = "MIICXAIBAAKBgQC5BtTGxmis7Ap3xM/7+T79Jkn32r1Lo4TSo5gAFHZQbhOr/rsTB3s3XqfZB9RWUWR7WEYzdTOqHqnJClTISvNgzJKEcYwo8MpJ5zOlSjvLjGyN422cBIxL+8sjY8TSBe41auYnybo3Nd7mopwkMNmNlMiQ96ZkoGae8ZLfbzPZVQIDAQABAoGAHRoZ9XnXlPs7WkM2g2dcpOyUzcs14uPBTHA2xCxzv4rQxUi3m/KdSsQ0mkpE956ts0jbIdTZX3SbN+fMFgTT6q0gThEBq3MFKqG+fZi0MrMXXRPByjdJDe2Xy4nm6ctcR8U6ldVRAZk5aJ/bDMmGucG4yfLXkgUJ71z+SQp8NrECQQDK1lz+sjEpJrPHaKyizz2okWTMgQrhCGikK9KINZquxhGLv0ojGLOsvQ8IrSoC7o5cWzLkXYSL5hfD74geGDHbAkEA6YVwCKnGybW5hDKy7+XdFPpy0mhLxcGMWo9LQKCCSTKXqj6IOH3HOvnciXN7NUf/TwN6mFzrsBHzyKrXJhAAjwJBAJzSITH1uNZ1CrfYcOirS6OBTapi9nNHWgfbrbkLoJ0Rm80sxvfdiES8Itx1bS65G63CANXYi7rR2XvuPJHv6NMCQDVXT6IK9ed5ZSj3U7xMq1VxZ+z7+eLwNRkyhiP7BgemUNKIeiE9SdcE4AVdpZUkHwNzbfuDriqHz0HVFFQTb60CQHhXlT6b1iU4jFgjdjTJiV6qnb2vCdVyE9OO8eX3YO9i3DzlPsQhpc/b1d/gAEN9QtqYaMnf0Ib6S/Oad/Z+iG4=";
System.out.println(encryptByPrivateKey("hello world!",privateKey));
}
}
四、RSA私钥加密PKCS1Padding
模式
public static String encryptByPrivateKey(String content,String privateKey) throws Exception {
byte[] keyBytes = Base64.decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey PrivateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, PrivateKey);
byte[] cipherText = cipher.doFinal(content.getBytes());
String cipherStr = Base64.encode(cipherText);
return cipherStr;
}