当前位置: 代码迷 >> 综合 >> java下RSA公钥pkcs1转pkcs8并且进行加密.
  详细解决方案

java下RSA公钥pkcs1转pkcs8并且进行加密.

热度:97   发布时间:2024-03-06 11:33:00.0

话不多说直接上代码.

 

package cn.xxx.util;import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;import javax.crypto.Cipher;import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Primitive;public class RSAUtils {static String pubKey ="" + "MIGJAoGBAPuIu5PNY+hwBWLNyV1+4rJALTo8i57X04M9+lad25rMrA4V/tdpf8jy\r\n" + "96h7hP+zZF1dWQiDVzUEg7cUhZ5kXIWn8MPUizkooYTCeaVZZKWWaDoOhupQFDx6\r\n" + "gL0se6BTQnEqVBkXIRet6dXiYmctzV+tc32VQdpoDmmbAAPKjpYdAgMBAAE=\r\n" + "";public static void main(String[] args) throws Exception {String str = "123456";System.out.println("result is :\n " + public_encrypt(str, pubKey));}/*** RSA加密:适合pkcs1 格式转 pkcs8 内容摘抄自stackoverflow,作者:President James K. Polk* @param str* @param publicKey* @return* @throws Exception*/public static String public_encrypt(String str, String publicKey) throws Exception {byte[] decoded = Base64.decodeBase64(publicKey);ASN1Primitive asn1Prime = new ASN1InputStream(decoded).readObject();org.bouncycastle.asn1.pkcs.RSAPublicKey rsaPub = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(asn1Prime);KeyFactory kf = KeyFactory.getInstance("RSA");PublicKey generatedPublic =  kf.generatePublic(new RSAPublicKeySpec(rsaPub.getModulus(), rsaPub.getPublicExponent()));//	X509EncodedKeySpec keySpec=new X509EncodedKeySpec(decoded);
//	
//	PublicKey generatedPublic = kf.generatePublic(keySpec);
//	Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, generatedPublic);String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));return outStr;}}