1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.yb.helper;
 
import org.apache.commons.codec.binary.Base64;
 
import javax.crypto.Cipher;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
 
public class RsaHelper {
    //    RsA秘钥加密
    public static String encrypt(String key, String str) throws Exception {
        try {
            byte[] decoded = Base64.decodeBase64(key + "");
 
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
 
            // RSA加密:RSA/ECB/NoPadding
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
 
            String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
 
            return outStr;
        }  catch (IOException e) {
            System.out.println(e.getMessage());
            return null;
        }
        // Base64编码的公钥
 
    }
 
}