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
| import lombok.extern.slf4j.Slf4j; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.HashMap; import java.util.Map;
@Slf4j public class RSAUtil { private static final String RSA_KEY_ALGORITHM = "RSA";
private static final String RSA_SIGNATURE_ALGORITHM = "SHA1withRSA"; private static final String RSA2_SIGNATURE_ALGORITHM = "SHA256withRSA";
private static final int KEY_SIZE = 1024;
public static Map<String, String> generateKey() { KeyPairGenerator keygen; try { keygen = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("RSA初始化密钥出现错误,算法异常"); } SecureRandom secrand = new SecureRandom(); secrand.setSeed("Alian".getBytes()); keygen.initialize(KEY_SIZE, secrand); KeyPair keyPair = keygen.genKeyPair(); byte[] pub_key = keyPair.getPublic().getEncoded(); String publicKeyStr = Base64.getEncoder().encodeToString(pub_key); byte[] pri_key = keyPair.getPrivate().getEncoded(); String privateKeyStr = Base64.getEncoder().encodeToString(pri_key); Map<String, String> keyPairMap = new HashMap<>(); keyPairMap.put("publicKeyStr", publicKeyStr); keyPairMap.put("privateKeyStr", privateKeyStr); return keyPairMap; }
public static String encryptByPublicKey(String data, String publicKeyStr) { try { byte[] decodePublicKeyByte = Base64.getDecoder().decode(publicKeyStr); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodePublicKeyByte); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bytesContent = data.getBytes(); int inputLen = bytesContent.length; int offLen = 0; int i = 0; ByteArrayOutputStream bops = new ByteArrayOutputStream(); while (inputLen - offLen > 0) { byte[] cache; if (inputLen - offLen > 117) { cache = cipher.doFinal(bytesContent, offLen, 117); } else { cache = cipher.doFinal(bytesContent, offLen, inputLen - offLen); } bops.write(cache); i++; offLen = 117 * i; } bops.close(); byte[] encryptedData = bops.toByteArray();
String encode = Base64.getEncoder().encodeToString(encryptedData); return encode; } catch (Exception e) { log.error("加密失败:", e); return ""; } }
public static String decryptByPrivateKey(String data, String privateKeyStr) throws Exception { try { byte[] priKey = Base64.getDecoder().decode(privateKeyStr); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey); KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytesContent = Base64.getDecoder().decode(data.getBytes()); int inputLen = bytesContent.length; int offLen = 0; int i = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while (inputLen - offLen > 0) { byte[] cache; if (inputLen - offLen > 128) { cache = cipher.doFinal(bytesContent, offLen, 128); } else { cache = cipher.doFinal(bytesContent, offLen, inputLen - offLen); } byteArrayOutputStream.write(cache); i++; offLen = 128 * i;
} byteArrayOutputStream.close(); byte[] byteArray = byteArrayOutputStream.toByteArray();
return new String(byteArray); } catch (Exception e) { log.error("解密失败,待加密内容:{}", data, e); return ""; } }
public static String sign(byte[] data, byte[] priKey, String signType) throws Exception { PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey); KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); String algorithm = RSA_KEY_ALGORITHM.equals(signType) ? RSA_SIGNATURE_ALGORITHM : RSA2_SIGNATURE_ALGORITHM; Signature signature = Signature.getInstance(algorithm); signature.initSign(privateKey); signature.update(data); byte[] sign = signature.sign(); return Base64.getEncoder().encodeToString(sign); }
public static boolean verify(byte[] data, byte[] sign, byte[] pubKey, String signType) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey); PublicKey publicKey = keyFactory.generatePublic(x509KeySpec); String algorithm = RSA_KEY_ALGORITHM.equals(signType) ? RSA_SIGNATURE_ALGORITHM : RSA2_SIGNATURE_ALGORITHM; Signature signature = Signature.getInstance(algorithm); signature.initVerify(publicKey); signature.update(data); return signature.verify(sign); }
public static void main(String[] args) throws Exception { Map<String, String> keyMap = RSAUtil.generateKey(); String publicKeyStr = keyMap.get("publicKeyStr"); String privateKeyStr = keyMap.get("privateKeyStr");
System.out.println("-----------------生成的公钥和私钥------------------------------"); System.out.println("获取到的公钥:" + publicKeyStr); System.out.println("获取到的私钥:" + privateKeyStr);
String data = "tranSeq=1920542585&amount=100&payType=wechat"; System.out.println("待签名的数据:" + data); String sign = RSAUtil.sign(data.getBytes(), Base64.getDecoder().decode(privateKeyStr), "RSA"); System.out.println("数字签名结果:" + sign);
boolean verify = RSAUtil.verify(data.getBytes(), Base64.getDecoder().decode(sign), Base64.getDecoder().decode(publicKeyStr), "RSA"); System.out.println("数字签名验证结果:" + verify);
String encryptText = encryptByPublicKey(data, publicKeyStr); System.out.println("密文:" + encryptText);
String decryptText = decryptByPrivateKey(encryptText, privateKeyStr); System.out.println("解密后信息:" + decryptText); } }
|