RSA加密的java實現2(交互IOS)
阿新 • • 發佈:2019-02-28
cep exce bject 設置 uri tin random exception androi
這裏的base64的依賴不一樣,一個是apache,一個是sun的 ,由於base64的依賴不同,導致在IOS中解析不了!
package com.handsight.platform.cipher; 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; import sun.misc.BASE64Decoder; //據說是sun公司未發布jar import sun.misc.BASE64Encoder; public class CreateSecretKey { public static final String KEY_ALGORITHM = "RSA"; private static final String PUBLIC_KEY = "RSAPublicKey"; private static finalString PRIVATE_KEY = "RSAPrivateKey"; public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; /** * * RSA最大加密明文大小 */ private static final int MAX_ENCRYPT_BLOCK = 117; /** * * RSA最大解密密文大小 */ private static final int MAX_DECRYPT_BLOCK = 128; // 獲得公鑰字符串 public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception { // 獲得map中的公鑰對象 轉為key對象 Key key = (Key) keyMap.get(PUBLIC_KEY); // 編碼返回字符串 return encryptBASE64(key.getEncoded()); } // 獲得私鑰字符串 public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception { // 獲得map中的私鑰對象 轉為key對象 Key key = (Key) keyMap.get(PRIVATE_KEY); // 編碼返回字符串 return encryptBASE64(key.getEncoded()); } // 獲取公鑰 public static PublicKey getPublicKey(String key) throws Exception { byte[] keyBytes; keyBytes = (new BASE64Decoder()).decodeBuffer(key); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } // 獲取私鑰 public static PrivateKey getPrivateKey(String key) throws Exception { byte[] keyBytes; keyBytes = (new BASE64Decoder()).decodeBuffer(key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } // 解碼返回byte public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } // 編碼返回字符串 public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } // ***************************簽名和驗證******************************* public static byte[] sign(byte[] data, String privateKeyStr) throws Exception { PrivateKey priK = getPrivateKey(privateKeyStr); Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initSign(priK); sig.update(data); return sig.sign(); } public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception { PublicKey pubK = getPublicKey(publicKeyStr); Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(pubK); sig.update(data); return sig.verify(sign); } // ************************加密解密************************** public static byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception { PublicKey publicKey = getPublicKey(publicKeyStr); Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); int inputLen = plainText.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; int i = 0; byte[] cache; while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(plainText, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptText = out.toByteArray(); out.close(); return encryptText; } public static byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception { PrivateKey privateKey = getPrivateKey(privateKeyStr); Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); int inputLen = encryptText.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(encryptText, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptText, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] plainText = out.toByteArray(); out.close(); return plainText; } public static void main(String[] args) { Map<String, Object> keyMap; byte[] cipherText; String input = "Hello World!"; try { keyMap = initKey(); String publicKey = getPublicKeyStr(keyMap); System.out.println("公鑰------------------"); System.out.println(publicKey); String privateKey = getPrivateKeyStr(keyMap); System.out.println("私鑰------------------"); System.out.println(privateKey); System.out.println("測試可行性-------------------"); System.out.println("明文=======" + input); cipherText = encrypt(input.getBytes(), publicKey); // 加密後的東西 System.out.println("密文=======" + new String(cipherText)); // 開始解密 byte[] plainText = decrypt(cipherText, privateKey); System.out.println("解密後明文===== " + new String(plainText)); System.out.println("驗證簽名-----------"); String str = "被簽名的內容"; System.out.println("\n原文:" + str); byte[] signature = sign(str.getBytes(), privateKey); boolean status = verify(str.getBytes(), signature, publicKey); System.out.println("驗證情況:" + status); } catch (Exception e) { e.printStackTrace(); } } public static Map<String, Object> initKey() 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; } }
測試:
package com.handsight.platform.cipher; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.Key; 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.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class TestRSA { // RSA算法對文件加密 public void encryptByRSA(String fileName, String saveFileName, String keyFileName) throws Exception { long start = System.currentTimeMillis(); try { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); String[] result = readKeyUtil(new File(keyFileName)); RSAPublicKey key2 = getPublicKey(result[0], result[1]); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, key2); byte[] wrappedKey = cipher.wrap(key); DataOutputStream out = new DataOutputStream(new FileOutputStream(saveFileName)); out.writeInt(wrappedKey.length); out.write(wrappedKey); InputStream in = new FileInputStream(fileName); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("總共耗時:" + (end - start)); } // RSA算法對文件解密 public void decryptByRSA(String fileName, String saveFileName, String keyFileName) throws Exception { try { DataInputStream in = new DataInputStream(new FileInputStream(fileName)); int length = in.readInt(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); String[] result = readKeyUtil(new File(keyFileName)); RSAPrivateKey key2 = getPrivateKey(result[0], result[1]); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.UNWRAP_MODE, key2); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(saveFileName); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //對數據塊加密 public void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException { int blockSize = cipher.getBlockSize(); int outputSize = cipher.getOutputSize(blockSize); byte[] inBytes = new byte[blockSize]; byte[] outBytes = new byte[outputSize]; int inLength = 0; boolean next = true; while (next) { inLength = in.read(inBytes); System.out.println(inLength); if (inLength == blockSize) { int outLength = cipher.update(inBytes, 0, blockSize, outBytes); out.write(outBytes, 0, outLength); } else { next = false; } } if (inLength > 0) { outBytes = cipher.doFinal(inBytes, 0, inLength); } else { outBytes = cipher.doFinal(); } out.write(outBytes); } //生成RSA密鑰對 public void generateRSAKey(String savePath) throws Exception { try { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keygen.initialize(RSA_KEYSIZE, random); KeyPair keyPair = keygen.generateKeyPair(); RSAPublicKey puk = (RSAPublicKey) keyPair.getPublic(); createXmlFile(puk.getModulus().toString(), puk.getPublicExponent().toString(), savePath + "\\public.xml"); RSAPrivateKey prk = (RSAPrivateKey) keyPair.getPrivate(); createXmlFile(prk.getModulus().toString(), prk.getPrivateExponent().toString(), savePath + "\\private.xml"); /* * OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(savePath * + "\\public.xml")); // 得到公鑰字符串 System.out.println(puk.getModulus()); * System.out.println(puk.getPublicExponent()); * System.out.println(prk.getModulus()); * System.out.println(prk.getPrivateExponent()); // 得到私鑰字符串 * osw.write(createXmlFile(puk.getModulus().toString(), * puk.getPublicExponent().toString())); osw.close(); osw = new * OutputStreamWriter(new FileOutputStream(savePath + "\\private.xml")); * osw.write(createXmlFile(prk.getModulus().toString(), * prk.getPrivateExponent().toString())); osw.close(); */ } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } /** * 使用模和指數生成RSA公鑰 * 註意:【此代碼用了默認補位方式,為RSA/None/PKCS1Padding,不同JDK默認的補位方式可能不同,如Android默認是RSA * /None/NoPadding】 * * @param modulus 模 * @param exponent 指數 * @return */ public static RSAPublicKey getPublicKey(String modulus, String exponent) { try { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 使用模和指數生成RSA私鑰 * 註意:【此代碼用了默認補位方式,為RSA/None/PKCS1Padding,不同JDK默認的補位方式可能不同,如Android默認是RSA * /None/NoPadding】 * * @param modulus 模 * @param exponent 指數 * @return */ public static RSAPrivateKey getPrivateKey(String modulus, String exponent) { try { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 生成xml字符串 * * @return * @throws Exception */ public static void createXmlFile(String Modulus, String Exponent, String filepath) throws Exception { Document document = DocumentHelper.createDocument(); Element root = document.addElement("root"); Element supercarElement = root.addElement("Modulus"); supercarElement.addText(Modulus); Element supercarElement2 = root.addElement("Exponent"); supercarElement2.addText(Exponent); // 寫入到一個新的文件中 writer(document, filepath); } /** * 把document對象寫入新的文件 * * @param document * @throws Exception */ public static void writer(Document document, String path) throws Exception { // 緊湊的格式 // 排版縮進的格式 OutputFormat format = OutputFormat.createPrettyPrint(); // 設置編碼 format.setEncoding("UTF-8"); // 創建XMLWriter對象,指定了寫出文件及編碼格式 XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(path)), "UTF-8"), format); // 寫入 writer.write(document); // 立即寫入 writer.flush(); // 關閉操作 writer.close(); } public String[] readKeyUtil(File file) throws DocumentException { // 創建saxReader對象 SAXReader reader = new SAXReader(); // 通過read方法讀取一個文件 轉換成Document對象 Document document = reader.read(file); // 獲取根節點元素對象 Element node = document.getRootElement(); Element ele = node.element("Modulus"); String Modulus = ele.getTextTrim(); Element ele1 = node.element("Exponent"); String Exponent = ele1.getTextTrim(); return new String[] { Modulus, Exponent }; } private static final int RSA_KEYSIZE = 1024; public static void main(String[] args) throws Exception { String path ="E:/home/handsight/aic/"; // 生成xml格式的公鑰和私鑰 new TestRSA().generateRSAKey(path); // 對文件進行加密 new TestRSA().encryptByRSA(path + "/12345.txt", path + "/456.txt", path + "/public.xml"); // 對文件進行解密 new TestRSA().decryptByRSA(path + "/456.txt", path + "/12345_new.txt", path + "/private.xml"); } }
RSA加密的java實現2(交互IOS)