RSA安全编码组件 @author SeanDragon
| 27 | * @author SeanDragon |
| 28 | */ |
| 29 | public final class ToolRSA { |
| 30 | private ToolRSA() { |
| 31 | throw new UnsupportedOperationException("我是工具类,别初始化我。。。"); |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * 非对称加密密钥算法 |
| 36 | */ |
| 37 | public static final String KEY_ALGORITHM = "RSA"; |
| 38 | |
| 39 | /** |
| 40 | * 公钥 |
| 41 | */ |
| 42 | private static final String PUBLIC_KEY = "RSAPublicKey"; |
| 43 | |
| 44 | /** |
| 45 | * 私钥 |
| 46 | */ |
| 47 | private static final String PRIVATE_KEY = "RSAPrivateKey"; |
| 48 | |
| 49 | /** |
| 50 | * RSA密钥长度 默认1024位, 密钥长度必须是64的倍数, 范围在512至65536位之间。 |
| 51 | */ |
| 52 | private static final int KEY_SIZE = 512; |
| 53 | |
| 54 | /** |
| 55 | * 私钥解密 |
| 56 | * |
| 57 | * @param data |
| 58 | * 待解密数据 |
| 59 | * @param key |
| 60 | * 私钥 |
| 61 | * |
| 62 | * @return byte[] 解密数据 |
| 63 | * |
| 64 | * @throws Exception |
| 65 | */ |
| 66 | public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { |
| 67 | // 取得私钥 |
| 68 | PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); |
| 69 | |
| 70 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); |
| 71 | |
| 72 | // 生成私钥 |
| 73 | PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); |
| 74 | |
| 75 | // 对数据解密 |
| 76 | Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); |
| 77 | |
| 78 | cipher.init(Cipher.DECRYPT_MODE, privateKey); |
| 79 | |
| 80 | return cipher.doFinal(data); |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * 公钥解密 |
| 85 | * |
| 86 | * @param data |
nothing calls this directly
no outgoing calls
no test coverage detected