?html
license裏就是一些註冊信息,鍵值對組成的字符串java
?算法
對稱加密:數組
DES,AES,加密解密都用一個祕鑰,速度快安全
非對稱機密app
RSA,能夠私鑰加密公鑰解密,也能夠公鑰機密私鑰解密,速度慢工具
注意:
RSA加密明文最大長度117字節,解密要求密文最大長度爲128字節,因此在加密和解密的過程當中須要分塊進行。
RSA加密對明文的長度是有限制的,若是加密數據過大會拋出異常:測試
?ui
常見加密算法編碼
DES?
??? DES是Data Encryption Standard(數據加密標準)的縮寫,DES算法爲密碼體制中的對稱密碼體制。它是由IBM公司研製的一種加密算法,美國國家標準局於1977年公佈把它做爲非機要部門使用的數據加密標準,二十年來,它一直活躍在國際保密通訊的舞臺上,扮演了十分重要的角色。
??? DES是一個分組加密算法,他以64位爲分組對數據加密。同時DES也是一個對稱算法:加密和解密用的是同一個算法。它的密匙長度是56位(由於每一個第8位都用做奇偶校驗),密匙能夠是任意的56位的數,並且能夠任意時候改變。其中有極少許的數被認爲是弱密匙,可是很容易避開他們。因此保密性依賴於密鑰。
??? 特色:分組比較短、密鑰過短、密碼生命週期短、運算速度較慢。
DES算法具備極高安全性,到目前爲止,除了用窮舉搜索法對DES算法進行攻擊外,尚未發現更有效的辦法。而56位長的密鑰的窮舉空間爲256,這意味着若是一臺計算機的速度是每一秒種檢測一百萬個密鑰,則它搜索徹底部密鑰就須要將近2285年的時間。
??? DES如今已經不視爲一種安全的加密算法,由於它使用的56位祕鑰太短,以現代計算能力,24小時內便可能被破解。也有一些分析報告提出了該算法的理論上的弱點,雖然實際狀況未必出現。該標準在最近已經被高級加密標準(AES)所取代。
?
AES
??? 高級加密標準(Advanced Encryption Standard,AES),又稱Rijndael加密法,是美國聯邦政府採用的一種區塊加密標準。這個標準用來替代原先的DES,已經被多方分析且廣爲全世界所使用。通過五年的甄選流程,高級加密標準由美國國家標準與技術研究院(NIST)於2001年11月26日發佈於FIPS PUB 197,並在2002年5月26日成爲有效的標準。2006年,高級加密標準已然成爲對稱密鑰加密中最流行的算法之一。
??? AES的區塊長度固定爲128 位元,密鑰長度則能夠是128,192或256位元。
?
RSA
??? RSA加密算法是一種非對稱加密算法。在公鑰加密標準和電子商業中RSA被普遍使用。RSA是1977年由羅納德·李維斯特(Ron Rivest)、阿迪·薩莫爾(Adi Shamir)和倫納德·阿德曼(Leonard Adleman)一塊兒提出的。當時他們三人都在麻省理工學院工做。RSA就是他們三人姓氏開頭字母拼在一塊兒組成的。
??? RSA算法的可靠性基於分解極大的整數是很困難的。假若有人找到一種很快的分解因子的算法的話,那麼用RSA加密的信息的可靠性就確定會極度降低。但找到這樣的算法的可能性是很是小的。今天只有短的RSA鑰匙纔可能被強力方式解破。到2008年爲止,世界上尚未任何可靠的攻擊RSA算法的方式。只要其鑰匙的長度足夠長,用RSA加密的信息其實是不能被解破的。
??? RSA算法利用兩個很大的質數相乘所產生的乘積來加密。這兩個質數不管哪個先與原文件編碼相乘,對文件加密,都可由另外一個質數再相乘來解密。但要用一個質數來求出另外一個質數,則是十分困難的。所以將這一對質數稱爲密鑰對(Key Pair)。在加密應用時,某個用戶老是將一個密鑰公開,讓需發信的人員將信息用其公共密鑰加密後發給該用戶,而一旦信息加密後,只有用該用戶一我的知道的私用密鑰才能解密。具備數字憑證身份的人員的公共密鑰可在網上查到,亦可在請對方發信息時主動將公共密鑰傳給對方,這樣保證在Internet上傳輸信息的保密和安全。
?
本文采用RSA加密算法加密license信息,能夠運行RSATester.java生成公鑰和私鑰。
RSAUtils.java
<pre name="code" class="java">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; /** *//** * <p> * RSA公鑰/私鑰/簽名工具包 * </p> * <p> * 羅納德·李維斯特(Ron [R]ivest)、阿迪·薩莫爾(Adi [S]hamir)和倫納德·阿德曼(Leonard [A]dleman) * </p> * <p> * 字符串格式的密鑰在未在特殊說明狀況下都爲BASE64編碼格式<br/> * 因爲非對稱加密速度極其緩慢,通常文件不使用它來加密而是使用對稱加密,<br/> * 非對稱加密算法能夠用來對對稱加密的密鑰加密,這樣保證密鑰的安全也就保證了數據的安全 * </p> * * @author IceWee * @date 2012-4-26 * @version 1.0 */ 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> * * @return * @throws Exception */ 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編碼) * * @return * @throws Exception */ public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.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 Base64Utils.encode(signature.sign()); } /** *//** * <p> * 校驗數字簽名 * </p> * * @param data 已加密數據 * @param publicKey 公鑰(BASE64編碼) * @param sign 數字簽名 * * @return * @throws Exception * */ public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { byte[] keyBytes = Base64Utils.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(Base64Utils.decode(sign)); } /** *//** * <P> * 私鑰解密 * </p> * * @param encryptedData 已加密數據 * @param privateKey 私鑰(BASE64編碼) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.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編碼) * @return * @throws Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64Utils.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編碼) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64Utils.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編碼) * @return * @throws Exception */ public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.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 密鑰對 * @return * @throws Exception */ public static String getPrivateKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY); return Base64Utils.encode(key.getEncoded()); } /** *//** * <p> * 獲取公鑰 * </p> * * @param keyMap 密鑰對 * @return * @throws Exception */ public static String getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return Base64Utils.encode(key.getEncoded()); } }
?
?Base64Utils.java
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; //import it.sauronsoftware.base64.Base64; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; //若報錯,編譯路徑移除jdk,再添加jdk /** *//** * <p> * BASE64編碼解碼工具包 * </p> * <p> * 依賴javabase64-1.3.1.jar 或 common-codec * </p> * * @author IceWee * @date 2012-5-19 * @version 1.0 */ public class Base64Utils { /** *//** * 文件讀取緩衝區大小 */ private static final int CACHE_SIZE = 1024; /** *//** * <p> * BASE64字符串解碼爲二進制數據 * </p> * * @param base64 * @return * @throws Exception */ public static byte[] decode(String base64) throws Exception { //return Base64.decode(base64.getBytes()); return new BASE64Decoder().decodeBuffer(base64); } /** *//** * <p> * 二進制數據編碼爲BASE64字符串 * </p> * * @param bytes * @return * @throws Exception */ public static String encode(byte[] bytes) throws Exception { //return new String(Base64.encode(bytes)); return new BASE64Encoder().encode(bytes); } /** *//** * <p> * 將文件編碼爲BASE64字符串 * </p> * <p> * 大文件慎用,可能會致使內存溢出 * </p> * * @param filePath 文件絕對路徑 * @return * @throws Exception */ public static String encodeFile(String filePath) throws Exception { byte[] bytes = fileToByte(filePath); return encode(bytes); } /** *//** * <p> * BASE64字符串轉回文件 * </p> * * @param filePath 文件絕對路徑 * @param base64 編碼字符串 * @throws Exception */ public static void decodeToFile(String filePath, String base64) throws Exception { byte[] bytes = decode(base64); byteArrayToFile(bytes, filePath); } /** *//** * <p> * 文件轉換爲二進制數組 * </p> * * @param filePath 文件路徑 * @return * @throws Exception */ public static byte[] fileToByte(String filePath) throws Exception { byte[] data = new byte[0]; File file = new File(filePath); if (file.exists()) { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); data = out.toByteArray(); } return data; } /** *//** * <p> * 二進制數據寫文件 * </p> * * @param bytes 二進制數據 * @param filePath 文件生成目錄 */ public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { InputStream in = new ByteArrayInputStream(bytes); File destFile = new File(filePath); // if (!destFile.getParentFile().exists()) { // destFile.getParentFile().mkdirs(); // } destFile.createNewFile(); OutputStream out = new FileOutputStream(destFile); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); } }
?
RSATester.java
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 = "這是一行測試RSA數字簽名的無心義文字"; System.out.println("原文字:\r\n" + source); byte[] data = source.getBytes(); 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); } }
?
運行此類生成license?
LicenseGenerator.java
import java.io.File; /** * 生成license * @author zhao * 2014.6.15 */ public class LicenseGenerator { /** * serial:由客戶提供 * timeEnd:過時時間 */ private static String licensestatic = "serial=568b8fa5cdfd8a2623bda1d8ab7b7b34;" + "timeEnd=1404057600000"; private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaa8y9g+ioR2OSs8njT5uCGWm0YmOA1elSu/P5\n" + "D3XYPCHsUPab74V5Og+NEZeTk9/LtG+jPSpKekTWm67gS2lQYWoygTwnoWsr4woaqNXmWw7L8Ty0\n" + "LQFTojZgyynvu2RSIJp4c76z6SV/khiP/ireGtt8uzXPswPO5uaPU38tQQIDAQAB"; /** * RSA算法 * 公鑰和私鑰是一對,此處只用私鑰加密 */ public static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJprzL2D6KhHY5KzyeNPm4IZabRi\n" + "Y4DV6VK78/kPddg8IexQ9pvvhXk6D40Rl5OT38u0b6M9Kkp6RNabruBLaVBhajKBPCehayvjChqo\n" + "1eZbDsvxPLQtAVOiNmDLKe+7ZFIgmnhzvrPpJX+SGI/+Kt4a23y7Nc+zA87m5o9Tfy1BAgMBAAEC\n" + "gYAVnlfohEoTHQN0q1TtTNzRhutEhK23gLsMiSGr0Z1G64w4QFF2HT9LbHR25GqbD426QAWNDegY\n" + "yytN/DesUQJqNXx8vuEuqs7+MQDgKgJqpAx+Fg3Iwsk/SVjq7meaSVGCgPKhtWHJk5oXoRMpsrlT\n" + "AwUjpdpAZXIIKW3mrqkW0QJBANq4INw6lZlqRFtxT4uzYQYtzmB/nxMnCbL2SQ4ZQ/4CWlQpOnR/\n" + "mH2JxIBCVtTADFlPM0DWF4aoqykYs9tu2X0CQQC0vgEk8DpkQbh1kgIyBGWCqYSKISTSXia0rbYo\n" + "FPnzdldgtZVirNGNmiJGL8RPz0YKpZNOg9FLHq/oYXSNFI4VAkAJ4OcbC0pWc4ZC2wtMs/1d2hPI\n" + "J/t3UfwOKTGDgYCgqFqMEpChUmIAyYgmgtiJI2NrZThbZVAKtPOGF6eH8anBAkAbxkL4wS3H8E1/\n" + "S7OoqgJLZO9oJpW4+hzqkPM4D5klb58Xzm+pXTNKllAEBx0cwpZZ1n3fh+Qmrg2MIUW+1FTNAkBt\n" + "WECowLUqW014M96WsFpiof7kjteOBNOjFyxhIbx2eT7//bnrADfq2Xu1/mSedUKrjGr/O+FRi7PO\n" + "u7WhF6C9"; public static void generator() throws Exception { System.err.println("私鑰加密——公鑰解密"); //String source = "568b8fa5cdfd8a2623bda1d8ab7b7b34"; System.out.println("原文字:\r\n" + licensestatic); byte[] data = licensestatic.getBytes(); byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey); System.out.println("加密後:\r\n" + new String(encodedData)); //加密後亂碼是正常的 Base64Utils.byteArrayToFile(encodedData, FileUtil.getBasePath()+File.separator+"license.dat"); System.out.println("license.dat:\r\n" + FileUtil.getBasePath()+File.separator+"license.dat"); //解密 byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey); String target = new String(decodedData); System.out.println("解密後: \r\n" + target); } public static void main(String[] args) throws Exception { generator(); } } ?
這裏把解密邏輯也放這裏了,實際上,公鑰和機密邏輯應該放在軟件運行的地方。
FileUtil.java
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.logging.Level; import java.util.logging.Logger; /** * 文件工具類 * @author zhao */ public class FileUtil { /** * 得到類的基路徑,打成jar包也能夠正確得到路徑 * @return */ public static String getBasePath(){ /* /D:/zhao/Documents/NetBeansProjects/docCompare/build/classes/ /D:/zhao/Documents/NetBeansProjects/docCompare/dist/bundles/docCompare/app/docCompare.jar */ String filePath = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile(); if (filePath.endsWith(".jar")){ filePath = filePath.substring(0, filePath.lastIndexOf("/")); try { filePath = URLDecoder.decode(filePath, "UTF-8"); //解決路徑中有空格%20的問題 } catch (UnsupportedEncodingException ex) { } } File file = new File(filePath); filePath = file.getAbsolutePath(); return filePath; } public static void main(String[] args) throws Exception { System.out.println(getBasePath()); } }
?
serial是軟件運行的地方提供的,
純java獲取CPU序列號,生成機器碼
http://happyqing.iteye.com/blog/2080402
?
參考
http://www.blogjava.net/icewee/archive/2012/05/19/378570.html
?
一個簡單的RSA加密類
http://yuncode.net/code/c_5049f78253ad762
RSAEncrypt.java
import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import javax.crypto.Cipher; /** * RSA加密類 */ public class RSAEncrypt { public static void main(String[] args) { try { RSAEncrypt encrypt = new RSAEncrypt(); String encryptText = "12345678"; KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); // Generate keys RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 私鑰 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 公鑰 byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes()); byte[] de = encrypt.decrypt(privateKey, e); System.out.println(encrypt.bytesToString(e)); System.out.println(); System.out.println(encrypt.bytesToString(de)); } catch (Exception e) { e.printStackTrace(); } } /** * byte數組轉爲string * @param encrytpByte * @return */ protected String bytesToString(byte[] encrytpByte) { String result = ""; for (Byte bytes : encrytpByte) { result += (char) bytes.intValue(); } return result; } /** * 加密方法 * @param publicKey * @param obj * @return */ protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) { if (publicKey != null) { try { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(obj); } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 解密方法 * @param privateKey * @param obj * @return */ protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) { if (privateKey != null) { try { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(obj); } catch (Exception e) { e.printStackTrace(); } } return null; } }
?
說明:
公鑰私鑰要本身生成,別拷別人的
Over
?
?