import cn.hutool.crypto.digest.BCrypt;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class PasswordUtil {
private PasswordUtil() {
}
private static final String CHARSET = "UTF-8";
private static final String KEY_ALGORITHM = "RSA";
private static final String PUBLIC_KEY = "公钥";
private static final String PRIVATE_KEY = "私钥";
public static void main(String[] args) {
String pwd = "P@ss1234";
try {
String encryptStr = publicEncrypt(pwd, getPublicKey());
System.out.println(encryptStr);
String decryptStr = privateDecrypt(encryptStr, getPrivateKey());
System.out.println(decryptStr);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
}
public static String publicEncrypt(String data, RSAPublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64URLSafeString(
rsaSplitCode(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCode(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
public static String encodePassword(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
public static boolean match(String password, String encodePassword) {
return BCrypt.checkpw(password, encodePassword);
}
public static String generatePassword(int len) {
if (len < 3) {
throw new IllegalArgumentException("字符串长度不能小于3");
}
char[] chArr = new char[len];
chArr[0] = (char) ('0' + StdRandom.uniform(0, 10));
chArr[1] = (char) ('A' + StdRandom.uniform(0, 26));
chArr[2] = (char) ('a' + StdRandom.uniform(0, 26));
chArr[3] = (char) ('~' + StdRandom.uniform(0, 26));
char[] codes =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '~', '!', '@', '#', '$', '%', '^', '&',
'*', '(', ')', '\\', ']', '[', '{', '}', ';', '\'',
':', '\"', '<', '>', ',', '.', '/', '?', '.', '+',
'-'};
for (int i = 3; i < len; i++) {
chArr[i] = codes[StdRandom.uniform(0, codes.length)];
}
for (int i = 0; i < len; i++) {
int r = i + StdRandom.uniform(len - i);
char temp = chArr[i];
chArr[i] = chArr[r];
chArr[r] = temp;
}
return new String(chArr) + "@";
}
public static String rsaDecrypt(String pwd) {
try {
return privateDecrypt(pwd, getPrivateKey());
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
return "";
}
public static RSAPublicKey getPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(PUBLIC_KEY));
return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
}
public static RSAPrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(PRIVATE_KEY));
return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
}
private static byte[] rsaSplitCode(Cipher cipher, int mode, byte[] data, int keySize) {
int maxBlock;
if (mode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (data.length > offSet) {
if (data.length - offSet > maxBlock) {
buff = cipher.doFinal(data, offSet, maxBlock);
} else {
buff = cipher.doFinal(data, offSet, data.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
}
byte[] resultData = out.toByteArray();
IOUtils.closeQuietly(out);
return resultData;
}
}
import java.util.Random;
public final class StdRandom {
private static Random random;
private static long seed;
static {
seed = System.currentTimeMillis();
random = new Random(seed);
}
private StdRandom() {}
public static void setSeed(long s){
seed = s;
random = new Random(seed);
}
public static long getSeed(){
return seed;
}
public static double uniform(){
return random.nextDouble();
}
public static int uniform(int N){
return random.nextInt(N);
}
public static double random(){
return uniform();
}
public static int uniform(int a,int b){
return a + uniform(b - a);
}
public static double uniform(double a,double b){
return a + uniform() * (b - a);
}
}