MCPcopy Create free account
hub / github.com/ZTFtrue/My-note / RSAUtil

Class RSAUtil

android/RSAUtil.java:22–131  ·  view source on GitHub ↗

Android 这里和java 是不完全一样的

Source from the content-addressed store, hash-verified

20 * Android 这里和java 是不完全一样的
21 */
22public class RSAUtil {
23 /**
24 * RSA最大加密明文大小
25 */
26 private final static int MAX_ENCRYPT_BLOCK = 117;
27
28 private final static String thpubk = "5JLdcTOCLc2r9Y6jRI1/MnJfjhNQ6I4dwblHyzaEquxM8qo5QvYydDE+wIDAQAB";
29 /**
30 * RSA最大加密明文大小
31 */
32 private final static String thprik = "lalalalalla";
33 /**
34 * RSA最大解密密文大小
35 */
36 private final static int MAX_DECRYPT_BLOCK = 128;
37
38 /**
39 * 获取公钥
40 *
41 * @param publicKey 公钥字符串
42 * @return
43 */
44 public static PublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
45 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
46 byte[] decodedKey = Base64.decode(publicKey.getBytes(), Base64.NO_WRAP);
47 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
48 return keyFactory.generatePublic(keySpec);
49 }
50 /**
51 * 获取私钥
52 *
53 * @param privateKey 私钥字符串
54 * @return
55 */
56 public static PrivateKey getPrivateKey(String privateKey) throws Exception {
57 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
58 byte[] decodedKey = Base64.decode(privateKey.getBytes(),Base64.NO_WRAP);
59 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
60 return keyFactory.generatePrivate(keySpec);
61 }
62
63
64 /**
65 * RSA加密
66 *
67 * @param data 待加密数据
68 * @return
69 */
70 public static String encrypt(String data) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
71 PublicKey publicKey = getPublicKey(thpubk);
72 Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
73 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
74 int inputLen = data.getBytes().length;
75 ByteArrayOutputStream out = new ByteArrayOutputStream();
76 int offset = 0;
77 byte[] cache;
78 int i = 0;
79 // 对数据分段加密

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected