java使用RSA,公钥加密
作者:互联网
import sun.misc.BASE64Decoder; import javax.crypto.Cipher; import java.security.*; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; public class RSAUtils { //公钥加密 public static String encrypt(String content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding" cipher.init(Cipher.ENCRYPT_MODE, publicKey); java.util.Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(cipher.doFinal(content.getBytes())); } public static PublicKey getPublicKey(String key) throws Exception { byte[] keyBytes; keyBytes = (new BASE64Decoder()).decodeBuffer(key); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } }
标签:公钥,java,keyBytes,RSA,publicKey,Cipher,import 来源: https://blog.51cto.com/chend/2694994