验签和加密解密方法不一样,下面代码只进行加密解密。
Java与php进行加密填充的格式不一样,Java为 RSA/NONE/NoPadding,PHP为 RSA/ECB/PKCS1Padding。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @author hp
*/
public class SecurityUtils {
private static final Logger log=LoggerFactory.getLogger(SecurityUtils.class);
//字符串进行加密算法的名称
public static final String ALGORITHM = "RSA";
//字符串进行加密填充的名称
public static final String PADDING = "RSA/NONE/NoPadding";
//字符串持有安全提供者的名称
public static final String PROVIDER = "BC";
//私钥
public static final String PRIVATE_KEY ="私钥字符串";
//公钥
public static final String PUBLIC_KEY = "公钥字符串";
/**
* 私钥
* 将字符串进行RSA加密
*
* @param text
* @return
*/
public static String encrypt(String text) {
String cipherTextBase64 = "";
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(PRIVATE_KEY));
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(text.getBytes());
cipherTextBase64 = Base64.encode(cipherText);
} catch (Exception e) {
log.info("[字符串进行RSA加密出现异常:{}]", e);
}
return cipherTextBase64;
}
/**
* 公钥
* 将字符串进行RSA解密
*
* @param str
* @return
*/
public static String decrypt(String str) {
byte[] dectyptedText = null;
try {
BASE64Decoder base64Decoder= new BASE64Decoder();
byte[] buffer= base64Decoder.decodeBuffer(PUBLIC_KEY);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer);
PublicKey publickey=keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, publickey);
byte[] text = Base64.decode(str);
dectyptedText = cipher.doFinal(text);
} catch (Exception e) {
log.info("[字符串进行RSA解密出现异常:{}]", e);
}
return new String(dectyptedText);
}
}