數字簽名演算法的具體使用測試
阿新 • • 發佈:2019-02-07
程式碼:
RSAUtils.java
package com.util; import java.io.ByteArrayOutputStream; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; public class RSAUtils { /* * 加密演算法RSA */ public static final String KEY_ALGORITHM = "RSA"; /* * 簽名演算法 */ public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; /* * 獲取公鑰的key */ private static final String PUBLIC_KEY = "RSAPublicKey"; /* * 獲取私鑰的key */ private static final String PRIVATE_KEY = "RSAPrivateKey"; /* * RSA最大加密明文大小 */ private static final int MAX_ENCRYPT_BLOCK = 117; /* * RSA最大解密密文大小 */ private static final int MAX_DECRYPT_BLOCK = 128; /* * <p> * 生成金鑰對(公鑰和私鑰) * </p> */ public static Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /* * <p> * 用私鑰對資訊生成數字簽名 * </p> * * @param data 已加密資料 * @param privateKey 私鑰(BASE64編碼) */ public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data); return Base64.encode(signature.sign()); } /* * <p> * 校驗數字簽名 * </p> * * @param data 已加密資料 * @param publicKey 公鑰(BASE64編碼) * @param sign 數字簽名 * */ public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicK); signature.update(data); return signature.verify(Base64.decode(sign)); } /* * <P> * 私鑰解密 * </p> * * @param encryptedData 已加密資料 * @param privateKey 私鑰(BASE64編碼) */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對資料分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /* * <p> * 公鑰解密 * </p> * * @param encryptedData 已加密資料 * @param publicKey 公鑰(BASE64編碼) */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對資料分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /* * <p> * 公鑰加密 * </p> * * @param data 源資料 * @param publicKey 公鑰(BASE64編碼) */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 對資料加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對資料分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } /* * <p> * 私鑰加密 * </p> * * @param data 源資料 * @param privateKey 私鑰(BASE64編碼) */ public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對資料分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } /* * <p> * 獲取私鑰 * </p> * * @param keyMap 金鑰對 */ public static String getPrivateKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY); return Base64.encode(key.getEncoded()); } /* * <p> * 獲取公鑰 * </p> * * @param keyMap 金鑰對 */ public static String getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return Base64.encode(key.getEncoded()); } }
Base64.java(Base64編碼)
package com.util; public class Base64 { private static char[] Base64Code = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static byte[] Base64Decode = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 63, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1 }; public static String encode(byte[] b) { int code = 0; if (b == null) return null; StringBuffer sb = new StringBuffer((b.length - 1) / 3 << 6); for (int i = 0; i < b.length; i++) { code |= b[i] << 16 - i % 3 * 8 & 255 << 16 - i % 3 * 8; if ((i % 3 != 2) && (i != b.length - 1)) continue; sb.append(Base64Code[((code & 0xFC0000) >>> 18)]); sb.append(Base64Code[((code & 0x3F000) >>> 12)]); sb.append(Base64Code[((code & 0xFC0) >>> 6)]); sb.append(Base64Code[(code & 0x3F)]); code = 0; } if (b.length % 3 > 0) sb.setCharAt(sb.length() - 1, '='); if (b.length % 3 == 1) sb.setCharAt(sb.length() - 2, '='); return sb.toString(); } public static byte[] decode(String code) { if (code == null) return null; int len = code.length(); if (len % 4 != 0) throw new IllegalArgumentException("Base64 string length must be 4*n"); if (code.length() == 0) return new byte[0]; int pad = 0; if (code.charAt(len - 1) == '=') pad++; if (code.charAt(len - 2) == '=') pad++; int retLen = len / 4 * 3 - pad; byte[] ret = new byte[retLen]; for (int i = 0; i < len; i += 4) { int j = i / 4 * 3; char ch1 = code.charAt(i); char ch2 = code.charAt(i + 1); char ch3 = code.charAt(i + 2); char ch4 = code.charAt(i + 3); int tmp = Base64Decode[ch1] << 18 | Base64Decode[ch2] << 12 | Base64Decode[ch3] << 6 | Base64Decode[ch4]; ret[j] = (byte)((tmp & 0xFF0000) >> 16); if (i < len - 4) { ret[(j + 1)] = (byte)((tmp & 0xFF00) >> 8); ret[(j + 2)] = (byte)(tmp & 0xFF); } else { if (j + 1 < retLen) ret[(j + 1)] = (byte)((tmp & 0xFF00) >> 8); if (j + 2 < retLen) ret[(j + 2)] = (byte)(tmp & 0xFF); } } return ret; } }
RSATester.java(數字簽名測試類)
package com.util; import java.util.Map; public class RSATester { static String publicKey; static String privateKey; static { try { Map<String, Object> keyMap = RSAUtils.genKeyPair(); publicKey = RSAUtils.getPublicKey(keyMap); privateKey = RSAUtils.getPrivateKey(keyMap); System.err.println("公鑰: \n\r" + publicKey); System.err.println("私鑰: \n\r" + privateKey); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { //test(); testSign(); } /* * 公鑰加密,私鑰解密的簽名機制 */ static void test() throws Exception { System.err.println("公鑰加密——私鑰解密"); String source = "海哥"; System.out.println("\r加密前文字:\r\n" + source); byte[] data = source.getBytes(); //公鑰加密 byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey); System.out.println("加密後文字:\r\n" + new String(encodedData)); //私鑰解密 byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey); String target = new String(decodedData); System.out.println("解密後文字: \r\n" + target); } /* * 私鑰加密,公鑰解密的簽名機制(個人比較喜歡用這種) */ static void testSign() throws Exception { System.err.println("私鑰加密——公鑰解密"); //String source = "my Test -----200---測試RSA數字簽名的原始資料"; String source = "海馬汽車2017年5月20日"; System.out.println("原文字:\r\n" + source); byte[] data = source.getBytes("UTF-8"); //私鑰加密 byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey); System.out.println("加密後:\r\n" + new String(encodedData)); //公鑰解密 byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey); String target = new String(decodedData); System.out.println("解密後: \r\n" + target); System.err.println("私鑰簽名——公鑰驗證簽名"); String sign = RSAUtils.sign(encodedData, privateKey); System.err.println("簽名:\r" + sign); boolean status = RSAUtils.verify(encodedData, publicKey, sign); System.err.println("驗證結果:\r" + status); } }
測試結果: