Java-檔案加密傳輸(摘要+簽名)
阿新 • • 發佈:2020-07-15
Java-檔案加密傳輸(摘要+簽名)
檔案加密傳輸其實就是將檔案以二進位制格式進行傳輸。
其中加密檔案主要由:原始檔二進位制檔案、原始檔數字摘要、數字簽名、特徵碼等等組成。
摘要可確認檔案的唯一性,數字簽名則是對摘要進行了加密。
本文主要記錄使用RSA加密方式
其中生成RSA金鑰主要介紹二種方式:
1、安裝openssl情況下使用Linux命令生成
2、Java程式碼實現
一、公私鑰生成
1、linux
1、檢視openssl版本
openssl version -a
2、生成私鑰
openssl genrsa -out rsa_private_key.pem 2048
會生成rsa_private_key.pem私鑰檔案,私鑰檔案不能使用
3、生成公鑰
openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -puboutopenssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
私鑰檔案不能使用
4、私鑰檔案PKCS#8編碼
openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem
此處生成的私鑰檔案方可用於Java
2、Java
importjava.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException;import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import org.apache.commons.codec.binary.Base64; public class RSAEncrypt { /** * 位元組資料轉字串專用集合 */ private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; private static final String PRIVATE_BEGIN = "-----BEGIN PRIVATE KEY-----"; private static final String PRIVATE_END = "-----END PRIVATE KEY-----"; private static final String PUBLIC_BEGIN = "-----BEGIN PUBLIC KEY-----"; private static final String PUBLIC_END = "-----END PUBLIC KEY-----"; /** * 1、隨機生成金鑰對 * * @param filePath 金鑰存放目錄 */ public void genKeyPair(String filePath) { // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA演算法生成物件 KeyPairGenerator keyPairGen = null; try { keyPairGen = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // 初始化金鑰對生成器,金鑰大小為96-1024位 keyPairGen.initialize(1024, new SecureRandom()); // 生成一個金鑰對,儲存在keyPair中 KeyPair keyPair = keyPairGen.generateKeyPair(); // 得到私鑰 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到公鑰 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); try { // 得到公鑰字串 Base64 base64 = new Base64(); String publicKeyString = new String(base64.encode(publicKey.getEncoded())); // 得到私鑰字串 String privateKeyString = new String(base64.encode(privateKey.getEncoded())); // 將金鑰對寫入到檔案 FileWriter pubfw = new FileWriter(filePath + "\\publicKey.pem"); FileWriter prifw = new FileWriter(filePath + "\\privateKey.pem"); BufferedWriter pubbw = new BufferedWriter(pubfw); BufferedWriter pribw = new BufferedWriter(prifw); pubbw.write(publicKeyString); pribw.write(privateKeyString); pubbw.flush(); pubbw.close(); pubfw.close(); pribw.flush(); pribw.close(); prifw.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 2、從本地檔案中讀取公鑰 * * @param path 公鑰路徑 * @return 公鑰字串 * @throws Exception 異常資訊 */ public String loadPublicKeyByFile(String path) throws Exception { try { BufferedReader br = new BufferedReader(new FileReader(path)); String readLine = null; StringBuilder sb = new StringBuilder(); while ((readLine = br.readLine()) != null) { // 去除公鑰頭部底部 if (!readLine.equals(PUBLIC_BEGIN) && !readLine.equals(PUBLIC_END)) { sb.append(readLine); } } br.close(); return sb.toString(); } catch (IOException e) { throw new Exception("公鑰資料流讀取錯誤"); } catch (NullPointerException e) { throw new Exception("公鑰輸入流為空"); } } /** * 3、字串公鑰轉公鑰物件 * * @param publicKeyStr 公鑰字串型別 * @return 公鑰物件 * @throws Exception 異常資訊 */ public RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception { try { Base64 base64 = new Base64(); byte[] buffer = base64.decode(publicKeyStr); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("無此演算法"); } catch (InvalidKeySpecException e) { throw new Exception("公鑰非法"); } catch (NullPointerException e) { throw new Exception("公鑰資料為空"); } } /** * 4、從本地檔案中讀取私鑰 * * @param path 私鑰檔案路徑 * @return 私鑰字串 * @throws Exception 異常資訊 */ public String loadPrivateKeyByFile(String path) throws Exception { try { BufferedReader br = new BufferedReader(new FileReader(path)); String readLine = null; StringBuilder sb = new StringBuilder(); while ((readLine = br.readLine()) != null) { //去除私鑰頭部底部 if (!readLine.equals(PRIVATE_BEGIN) && !readLine.equals(PRIVATE_END)) { sb.append(readLine); } else { } } br.close(); return sb.toString(); } catch (IOException e) { throw new Exception("私鑰資料讀取錯誤"); } catch (NullPointerException e) { throw new Exception("私鑰輸入流為空"); } } /** * 5、字串公鑰轉公鑰物件 * * @param privateKeyStr 私鑰字串型別 * @return 私鑰物件 * @throws Exception 異常資訊 */ public RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception { try { Base64 base64 = new Base64(); byte[] buffer = base64.decode(privateKeyStr); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("無此演算法"); } catch (InvalidKeySpecException e) { throw new Exception("私鑰非法"); } catch (NullPointerException e) { throw new Exception("私鑰資料為空"); } } /** * 6、公鑰加密過程 * * @param publicKey 公鑰 * @param plainTextData 明文資料 * @return * @throws Exception 加密過程中的異常資訊 */ public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception { if (publicKey == null) { throw new Exception("加密公鑰為空, 請設定"); } Cipher cipher = null; try { // 使用預設RSA cipher = Cipher.getInstance("RSA"); // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] output = cipher.doFinal(plainTextData); return output; } catch (NoSuchAlgorithmException e) { throw new Exception("無此加密演算法"); } catch (NoSuchPaddingException e) { e.printStackTrace(); return null; } catch (InvalidKeyException e) { throw new Exception("加密公鑰非法,請檢查"); } catch (IllegalBlockSizeException e) { throw new Exception("明文長度非法"); } catch (BadPaddingException e) { throw new Exception("明文資料已損壞"); } } /** * 7、私鑰加密過程 * * @param privateKey 私鑰 * @param plainTextData 明文資料 * @return * @throws Exception 加密過程中的異常資訊 */ public byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception { if (privateKey == null) { throw new Exception("加密私鑰為空, 請設定"); } Cipher cipher = null; try { // 使用預設RSA cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] output = cipher.doFinal(plainTextData); return output; } catch (NoSuchAlgorithmException e) { throw new Exception("無此加密演算法"); } catch (NoSuchPaddingException e) { e.printStackTrace(); return null; } catch (InvalidKeyException e) { throw new Exception("加密私鑰非法,請檢查"); } catch (IllegalBlockSizeException e) { throw new Exception("明文長度非法"); } catch (BadPaddingException e) { throw new Exception("明文資料已損壞"); } } /** * 8、私鑰解密過程 * * @param privateKey 私鑰 * @param cipherData 密文資料 * @return 明文 * @throws Exception 解密過程中的異常資訊 */ public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception { if (privateKey == null) { throw new Exception("解密私鑰為空, 請設定"); } Cipher cipher = null; try { // 使用預設RSA cipher = Cipher.getInstance("RSA"); // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] output = cipher.doFinal(cipherData); return output; } catch (NoSuchAlgorithmException e) { throw new Exception("無此解密演算法"); } catch (NoSuchPaddingException e) { e.printStackTrace(); return null; } catch (InvalidKeyException e) { throw new Exception("解密私鑰非法,請檢查"); } catch (IllegalBlockSizeException e) { throw new Exception("密文長度非法"); } catch (BadPaddingException e) { throw new Exception("密文資料已損壞"); } } /** * 9、公鑰解密過程 * * @param publicKey 公鑰 * @param cipherData 密文資料 * @return 明文 * @throws Exception 解密過程中的異常資訊 */ public byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception { if (publicKey == null) { throw new Exception("解密公鑰為空, 請設定"); } Cipher cipher = null; try { // 使用預設RSA cipher = Cipher.getInstance("RSA"); // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] output = cipher.doFinal(cipherData); return output; } catch (NoSuchAlgorithmException e) { throw new Exception("無此解密演算法"); } catch (NoSuchPaddingException e) { e.printStackTrace(); return null; } catch (InvalidKeyException e) { throw new Exception("解密公鑰非法,請檢查"); } catch (IllegalBlockSizeException e) { throw new Exception("密文長度非法"); } catch (BadPaddingException e) { throw new Exception("密文資料已損壞"); } } /** * 10、位元組資料轉十六進位制字串 * * @param data 輸入資料 * @return 十六進位制內容 */ public String byteArrayToString(byte[] data) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < data.length; i++) { // 取出位元組的高四位 作為索引得到相應的十六進位制識別符號 注意無符號右移 stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]); // 取出位元組的低四位 作為索引得到相應的十六進位制識別符號 stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]); if (i < data.length - 1) { stringBuilder.append(' '); } } return stringBuilder.toString(); } }
二、呼叫
/** * 生成加密後文件 * * @param oldFilePath 需要加密檔案路徑+名稱 * @param newFilePath 加密後文件路徑+名稱 * @param privatePath 私鑰檔案路徑+名稱 */ public void fileEncrypt(String oldFilePath, String newFilePath, String privatePath) { ByteUtil byteUtil = new ByteUtil(); //檔案格式:特徵碼+原始升級包長度+數字簽名長度+原始包內容+數字簽名 byte[] code = byteUtil.intToByteArray(0x9F2308DC); RSAEncrypt rsaEncrypt = new RSAEncrypt(); try { //1、特徵碼寫入 OutputStream out = new FileOutputStream(new File(newFilePath)); out.write(code, 0, 4); //2、原始升級包長度寫入 byte[] fileByte = byteUtil.File2byte(oldFilePath); int L1 = fileByte.length; byte[] a = byteUtil.intToByteArray(L1); out.write(a, 0, 4); //檔案摘要生成 MsgDigestDemo msgDigestDemo = new MsgDigestDemo(); MessageDigest md5Digest = MessageDigest.getInstance("MD5"); md5Digest.update(msgDigestDemo.fileBytes(oldFilePath)); byte[] md5Encoded = md5Digest.digest(); log.info("==========MD5摘要:{}==========", Base64.encodeBase64URLSafeString(md5Encoded)); String privateKey = rsaEncrypt.loadPrivateKeyByFile(privatePath); RSAPrivateKey privateKeyfile = rsaEncrypt.loadPrivateKeyByStr(privateKey); //生成簽名(摘要加密過程) byte[] signature = rsaEncrypt.encrypt(privateKeyfile, md5Encoded); //3、簽名長度 int L2 = signature.length; byte[] c = byteUtil.intToByteArray(L2); out.write(c, 0, 4); //4、原始升級包內容寫入 out.write(fileByte, 0, L1); //5、數字簽名寫入 out.write(signature, 0, L2); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
MD5摘要計算
public class MsgDigestDemo { public byte[] fileBytes(String filePath) { try { File file = new File(filePath); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); FileInputStream in = new FileInputStream(file); byte[] fileByte = new byte[1024]; int n; while ((n = in.read(fileByte)) != -1) { out.write(fileByte, 0, n); } in.close(); byte[] data = out.toByteArray(); out.close(); return data; } catch (IOException e) { e.printStackTrace(); } return null; } }