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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
| @Slf4j public class RSAUtils {
private static final String RSA_KEY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final int KEY_SIZE = 2048;
private static final int BASE_SIZE = 8;
private static final int MAX_ENCRYPT_BLOCK = KEY_SIZE / BASE_SIZE - 11;
private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / BASE_SIZE;
private static Map<String, String> initKey() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM); keygen.initialize(KEY_SIZE); KeyPair keys = keygen.genKeyPair();
byte[] pubKey = keys.getPublic().getEncoded(); String publicKeyString = Base64.encodeBase64String(pubKey);
byte[] priKey = keys.getPrivate().getEncoded(); String privateKeyString = Base64.encodeBase64String(priKey);
Map<String, String> keyPairMap = new HashMap<>(); keyPairMap.put("publicKeyString", publicKeyString); keyPairMap.put("privateKeyString", privateKeyString);
return keyPairMap; }
public static byte[] decodeBase64(String key) { return Base64.decodeBase64(key); }
public static PublicKey getPublicKey(String publicKey) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes()); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey); return keyFactory.generatePublic(keySpec); }
public static PrivateKey getPrivateKey(String privateKey) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey); return keyFactory.generatePrivate(keySpec); }
public static String encryptByPubKey(String data, String publicKey) throws Exception { byte[] pubKey = RSAUtils.decodeBase64(publicKey); byte[] enSign = encryptByPubKey(data.getBytes(), pubKey); return Base64.encodeBase64String(enSign); }
public static byte[] encryptByPubKey(byte[] data, byte[] pubKey) throws Exception { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey); KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); PublicKey publicKey1 = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey1);
int offSet = 0; byte[] resultBytes = {}; byte[] cache = {}; int inputLength = data.length; while (inputLength - offSet > 0) { if (inputLength - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); offSet += MAX_ENCRYPT_BLOCK; } else { cache = cipher.doFinal(data, offSet, inputLength - offSet); offSet = inputLength; } resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length); System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length); } return resultBytes; }
public static byte[] decryptByPriKey(byte[] data, byte[] priKey) throws Exception { PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey); KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); PrivateKey privateKey1 = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey1);
int inputLen = data.length;
int offSet = 0; byte[] cache; int i = 0; byte[] decryptedData = new byte[0];
try(ByteArrayOutputStream out = new ByteArrayOutputStream()){ while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } decryptedData = out.toByteArray(); }catch (Exception e){ log.error(e.getMessage(),e); throw e; }
return decryptedData; }
public static String decryptByPriKey(String data, String privateKey) throws Exception { byte[] priKey = RSAUtils.decodeBase64(privateKey); byte[] design = decryptByPriKey(Base64.decodeBase64(data), priKey); return new String(design); }
public static String sign(SignVo signVo, String privateKey) throws Exception { PrivateKey privateKeys = getPrivateKey(privateKey); String data = toSignStrMap(signVo); byte[] keyBytes = privateKeys.getEncoded(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); PrivateKey key = keyFactory.generatePrivate(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(key); signature.update(data.getBytes()); return new String(Base64.encodeBase64(signature.sign())); }
public static boolean verify(SignVo signVo, String publicKey, String sign) throws Exception { PublicKey publicKeys = getPublicKey(publicKey); String srcData = toSignStrMap(signVo); byte[] keyBytes = publicKeys.getEncoded(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); PublicKey key = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(key); signature.update(srcData.getBytes()); return signature.verify(Base64.decodeBase64(sign.getBytes())); }
public static String toSignStrMap(SignVo signVo) { StringBuilder sb = new StringBuilder(); sb.append(signVo.getSignA()).append("&").append(signVo.getSignB()).append("&").append(signVo.getSignC()); return sb.toString(); }
public static void main(String[] args) { try { Map<String, String> keyMap = initKey(); String publicKeyString = keyMap.get("publicKeyString"); String privateKeyString = keyMap.get("privateKeyString"); System.out.println("公钥:" + publicKeyString); System.out.println("私钥:" + privateKeyString);
String data = "{\"code\":\"0000\",\"data\":{\"list\":[{\"address\":\"互联网创业中心\",\"amount\":120000.0,\"applicationDate\":1594174666000,\"createDate\":1594174666000,\"ecCode\":\"MC0001\",\"ecName\":\"ARJ\",\"ecOrderNumber\":\"20202070817261111\",\"orderNumber\":\"AR202007081017453500\",\"payOrderNumber\":\"\",\"phone\":\"1860000000\",\"productList\":[{\"name\":\"小米18\",\"number\":2,\"pictureUrl\":\"https://dss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/93d9d2b0e5373b93ca5032d13866fd14_254_144.jpg\",\"price\":60000.0}],\"repayDay\":\"08\",\"stageAmount\":40000.0,\"stageNumber\":3,\"status\":\"01\",\"total\":2,\"updateDate\":1594261066000,\"userId\":\"56f72c55c0cc11ea8c81fa163efd3ee0\"},{\"address\":\"互联网创业中心\",\"amount\":60000.0,\"applicationDate\":1594173896000,\"createDate\":1594173896000,\"ecCode\":\"MC0001\",\"ecName\":\"ARJ\",\"ecOrderNumber\":\"20202070817260000\",\"orderNumber\":\"AR202007081004565300\",\"payOrderNumber\":\"\",\"phone\":\"137777777\",\"productList\":[{\"name\":\"华为P40\",\"number\":2,\"pictureUrl\":\"https://consumer-img.huawei.com/content/dam/huawei-cbg-site/common/mkt/pdp/phones/p40-pro-plus-specs/cn/dimage.jpg\",\"price\":30000.0}],\"repayDay\":\"08\",\"stageAmount\":20000.0,\"stageNumber\":3,\"status\":\"01\",\"total\":2,\"updateDate\":1594260296000,\"userId\":\"56f72c55c0cc11ea8c81fa163efd3ee0\"}]},\"msg\":\"成功\",\"showMsg\":\"success\"}"; String encrypt = RSAUtils.encryptByPubKey(data, publicKeyString); String decrypt = RSAUtils.decryptByPriKey(encrypt, privateKeyString);
System.out.println("加密前:" + data); System.out.println("加密后:" + encrypt); System.out.println("解密后:" + decrypt);
SignVo signVo = new SignVo(); signVo.setSignA("testA"); signVo.setSignB("testB"); signVo.setSignC("testC"); String sign = RSAUtils.sign(signVo,privateKeyString);
System.out.println("签名:"+sign);
boolean result = RSAUtils.verify(signVo,publicKeyString,sign);
System.out.println("验签结果:"+result);
} catch (Exception e) { e.printStackTrace(); } } } @Data class SignVo{
private String signA;
private String signB;
private String signC; }
|