一、前言
通过java.security.interfaces.RSAPrivateKey、java.security.interfaces.RSAPublicKey公私钥标准定义RSAUtil非对称公私钥密钥对工具类,详情下面代码示例。
二、代码示例
import java.security.KeyFactory;@b@import java.security.KeyPair;@b@import java.security.KeyPairGenerator;@b@import java.security.SecureRandom;@b@import java.security.interfaces.RSAPrivateKey;@b@import java.security.interfaces.RSAPublicKey;@b@import java.security.spec.PKCS8EncodedKeySpec;@b@import java.security.spec.X509EncodedKeySpec;@b@import java.util.HashMap;@b@import java.util.Map;@b@import javax.crypto.Cipher;@b@import org.apache.commons.lang.ArrayUtils;@b@import com.alibaba.fastjson.JSONObject;@b@@b@public class RSAUtil {@b@@b@ private static final String KEY_ALGORITHM = "RSA";@b@@b@ private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5',@b@ '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };@b@@b@ public static void main(String[] args) throws Exception {@b@ //获取非对称公私钥密钥对@b@ genKey();@b@ }@b@@b@ public static Map<String, String> genKey() throws Exception {@b@ Map<String, String> returnMap = new HashMap<String, String>();@b@ KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);@b@ SecureRandom random = new SecureRandom();@b@ keygen.initialize(1024, random);@b@ // 取得密钥对@b@ KeyPair kp = keygen.generateKeyPair();@b@ RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();@b@ String privateKeyString = bytesToHexStr(privateKey.getEncoded());@b@@b@ RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();@b@ String publicKeyString = bytesToHexStr(publicKey.getEncoded());@b@ returnMap.put("publicKey", publicKeyString);@b@ returnMap.put("privateKey", privateKeyString);@b@@b@ System.out.println("PUBLIC_KEY length:" + publicKeyString.length()@b@ + "\r\nPUBLIC_KEY:" + publicKeyString);@b@ System.out.println("PRIVATE_KEY length:" + privateKeyString.length()@b@ + "\r\nPRIVATE_KEY:" + privateKeyString);@b@@b@ return returnMap;@b@ }@b@@b@ public static RSAPublicKey getPublicKey(String publicKey) throws Exception {@b@ byte[] keyBytes = hexStrToBytes(publicKey);@b@ X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);@b@ KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);@b@ return (RSAPublicKey) keyFactory.generatePublic(spec);@b@ }@b@@b@ public static RSAPrivateKey getPrivateKey(String privateKey)@b@ throws Exception {@b@ byte[] keyBytes = hexStrToBytes(privateKey);@b@ PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);@b@ KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);@b@ return (RSAPrivateKey) keyFactory.generatePrivate(spec);@b@ }@b@@b@ public static String encrypt(Map<String, String> params, String publicKey)@b@ throws Exception {@b@ JSONObject object = new JSONObject();@b@ object.putAll(params);@b@ return encrypt(object.toString(), publicKey);@b@ }@b@@b@ public static String encrypt(String info, String publicKey)@b@ throws Exception {@b@ RSAPublicKey publickey = getPublicKey(publicKey);@b@ byte[] bytes = encrypt(info.getBytes("utf-8"), publickey);@b@ return bytesToHexStr(bytes);@b@ }@b@@b@ private static byte[] encrypt(byte[] text, RSAPublicKey pubRSA)@b@ throws Exception {@b@ Cipher cipher = Cipher.getInstance("RSA");@b@ cipher.init(Cipher.ENCRYPT_MODE, pubRSA);@b@ byte[] dataReturn = new byte[0];@b@ for (int i = 0; i < text.length; i += 245) {@b@ byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(text, i,@b@ i + 245));@b@ dataReturn = ArrayUtils.addAll(dataReturn, doFinal);@b@ }@b@ return dataReturn;@b@ }@b@@b@ public static String decrypt(String sign, String privateKey)@b@ throws Exception {@b@ RSAPrivateKey privatekey = getPrivateKey(privateKey);@b@ byte[] bytes = decrypt((hexStrToBytes(sign)), privatekey);@b@ return new String(bytes, "utf-8");@b@ }@b@@b@ private static byte[] decrypt(byte[] src, RSAPrivateKey prK)@b@ throws Exception {@b@ Cipher cipher = Cipher.getInstance("RSA");@b@ cipher.init(Cipher.DECRYPT_MODE, prK);@b@ byte[] dataReturn = new byte[0];@b@ for (int i = 0; i < src.length; i += 256) {@b@ byte[] doFinal = cipher.doFinal(ArrayUtils@b@ .subarray(src, i, i + 256));@b@ dataReturn = ArrayUtils.addAll(dataReturn, doFinal);@b@ }@b@ return dataReturn;@b@ }@b@@b@ /**@b@ * Transform the specified byte into a Hex String form.@b@ */@b@ private static final String bytesToHexStr(byte[] bcd) {@b@ StringBuffer s = new StringBuffer(bcd.length * 2);@b@ for (int i = 0; i < bcd.length; i++) {@b@ s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);@b@ s.append(bcdLookup[bcd[i] & 0x0f]);@b@ }@b@ return s.toString();@b@ }@b@@b@ /**@b@ * Transform the specified Hex String into a byte array.@b@ */@b@ private static final byte[] hexStrToBytes(String s) {@b@ byte[] bytes;@b@ bytes = new byte[s.length() / 2];@b@ for (int i = 0; i < bytes.length; i++) {@b@ bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),@b@ 16);@b@ }@b@ return bytes;@b@ }@b@@b@}
控制台打印结果如下
PUBLIC_KEY length:324@b@PUBLIC_KEY:30819F300D06092A864886F70D010101050003818D0030818902818100A238E11C637ED120516CAC482F18C72D91DB94C7C8A40D37B2C3C62E34E60C62F1CC1DC6859889D9C279B503F1722388AD906CF7264EB942CDAD83C230391E234158C3BFCBEBA23A0840187959DCDE013F9CA393F77F1FD3BFDF4F475587C547A495232F57E09FF590756E67D2D4CD55127935A66369806F0DAD0247549A16490203010001@b@PRIVATE_KEY length:1270@b@PRIVATE_KEY:30820277020100300D06092A864886F70D0101010500048202613082025D02010002818100A238E11C637ED120516CAC482F18C72D91DB94C7C8A40D37B2C3C62E34E60C62F1CC1DC6859889D9C279B503F1722388AD906CF7264EB942CDAD83C230391E234158C3BFCBEBA23A0840187959DCDE013F9CA393F77F1FD3BFDF4F475587C547A495232F57E09FF590756E67D2D4CD55127935A66369806F0DAD0247549A1649020301000102818032BCFB9BB77AE8C9E4EDCA8CE13E2CBE120ACDE416DB48CF0CF8B2B9AD0DEEFDDB86EE213393DC39E1DBD344227682AAB32EA3064253091ADDDDD18221371C3786B408E2C75A0D28A8F283859343FA3605447E4456254E26365EED59643CADFE2F6971AB5F4DC2261F4A539EEA8804FC3B9BE8D370B6F302A00F05F186232E69024100DEACE8D8031F93353DEBA82B17AD6748AF80D27B3DD73287E99F587E6A71327C61ED8D21594BE58B329554BA7B7887A1E5CE9DCDAF7279DC53D68BA6994384F7024100BA7FE61C42A130A159F6C3E191B8998A55C74C00D0EA3D6E8CC673058B923CA247614F34EC4ED24BC68D82F1ADE5CEB38AAE958E7FBB21BAC7016CF45B76AEBF02403EC865C631EB3F282DD339D11C95E99F16CCAD8BCDFDD4E3793D5248225ED42B39B92EA78E73D5BE8F7E872B2510F0BCF6FC7085C3C7F50FE81B7FB873521435024100A63AC5B1BEB9C98CA791493ACF15C8D5026BE7147B21ADABD192388762C5EF817D3A00CD5D2B4C49FA29BBE30A6AE0F82ACE3DC38B9A121056BCB08E84CF9E25024100C75D19F11028FD976E819E480BAA133638C89CC5BED636B1C439B780858957882ADB4D65AD4C07EF3691DDB2A01D9193C38DDE27DCE5BD138E35ED27B449DDDB