java与php,RSA加密解密对接

验签和加密解密方法不一样,下面代码只进行加密解密。

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);
	}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值