You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
udi-wms-java/src/main/java/com/glxp/api/util/RsaUtils.java

89 lines
3.1 KiB
Java

3 years ago
package com.glxp.api.util;
import cn.hutool.core.io.resource.ClassPathResource;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RsaUtils {
public static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtaHLiDtscnwyee4lG9jC" +
"8GUEZYIuBoz49W3GSy2LEOVpKRyiQNCjRmybvQS5qKdsb3pV720HQJnv/nQLnsg/" +
"vWbFc9L09fEeJdDZxQOf8D7CHeVgLd8+fh/GezQCVLijGlbAVORXOrFo5McdyOds" +
"LJey1x4HxIR13a79JHB7sdve14A2aS6bQ7NPWu8hM9LpJd1hylsXgdBpR+iX3DPF" +
"eep8Sx8jPnWfUfGF2pDNE3h1uz9RylGBYUz4tDPzz0IXO7vZkyUFXeslzKFDFcmh" +
"hbn1tobX+al4XvfRpjoCjST2mRfqCt4aNuBDM1LHMzyMBVJpfui91ikLGMgP4Gdf" +
"swIDAQAB";
/**
* RSA
*/
public static String privateKeyEncrypt(String str, String privateKey) throws Exception {
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(privateKey);
PrivateKey priKey = KeyFactory.getInstance("RSA").
generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, priKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes()));
return outStr;
}
/**
* RSA
*/
public static String publicKeyDecrypt(String str, String publicKey) throws Exception {
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(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 readFileContent(String fileName) {
ClassPathResource resource = new ClassPathResource("config.txt");
File file = new File(resource.getAbsolutePath());
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
return sbf.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return sbf.toString();
}
}