package net.foreworld.util; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import org.apache.commons.codec.binary.Base64; /** * * @author huangxin <3203317@qq.com> * */ public class RSACoder { public static final String RSA = "RSA"; /** * Client Mode * * @throws Exception */ private static void mode_cli() throws Exception { String message = "123456 hello 世界!"; String[] keys = genKey(); System.err.println("pubkey: " + keys[0]); System.err.println("prikey: " + keys[1]); // 私鑰加密 String edata = encrypt(Mode.CLIENT, keys[1], message); System.out.println("prikey encrypt: " + edata); // 公鑰解密 String ddata = decrypt(Mode.CLIENT, keys[0], edata); System.err.println("pubkey decrypt: " + ddata); } /** * Server Mode * * @throws Exception */ private static void mode_serv() throws Exception { String message = "654321 hello world!"; String[] keys = genKey(); System.err.println("pubkey: " + keys[0]); System.err.println("prikey: " + keys[1]); // 公鑰加密 String edata = encrypt(Mode.SERVER, keys[0], message); System.out.println("pubkey encrypt: " + edata); // 私鑰解密 String ddata = decrypt(Mode.SERVER, keys[1], edata); System.err.println("prikey decrypt: " + ddata); } public static void main(String[] args) throws Exception { mode_serv(); mode_cli(); } /** * * @return * @throws NoSuchAlgorithmException */ public static String[] genKey() throws NoSuchAlgorithmException { KeyPairGenerator genor = KeyPairGenerator.getInstance(RSA); genor.initialize(512); KeyPair pair = genor.generateKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) pair.getPublic(); RSAPrivateKey priKey = (RSAPrivateKey) pair.getPrivate(); return new String[] { encodeBase64String(pubKey.getEncoded()), encodeBase64String(priKey.getEncoded()) }; } /** * * @param b * @return */ public static String encodeBase64String(byte[] b) { return Base64.encodeBase64String(b); } /** * * @param s * @return */ public static byte[] decodeBase64(String s) { return Base64.decodeBase64(s); } /** * * @param mode * @param key * @param data * @return * @throws Exception */ public static String encrypt(Mode mode, String key, String data) throws Exception { KeyFactory factory = KeyFactory.getInstance(RSA); Cipher cipher = Cipher.getInstance(RSA); if (Mode.SERVER == mode) { X509EncodedKeySpec spec = new X509EncodedKeySpec(decodeBase64(key)); PublicKey pubKey = factory.generatePublic(spec); cipher.init(Cipher.ENCRYPT_MODE, pubKey); } else { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decodeBase64(key)); PrivateKey priKey = factory.generatePrivate(spec); cipher.init(Cipher.ENCRYPT_MODE, priKey); } byte[] result = cipher.doFinal(data.getBytes()); return encodeBase64String(result); } /** * * @param mode * @param key * @param data * @return * @throws Exception */ public static String decrypt(Mode mode, String key, String data) throws Exception { KeyFactory factory = KeyFactory.getInstance(RSA); Cipher cipher = Cipher.getInstance(RSA); if (Mode.SERVER == mode) { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decodeBase64(key)); PrivateKey priKey = factory.generatePrivate(spec); cipher.init(Cipher.DECRYPT_MODE, priKey); } else { X509EncodedKeySpec spec = new X509EncodedKeySpec(decodeBase64(key)); PublicKey pubKey = factory.generatePublic(spec); cipher.init(Cipher.DECRYPT_MODE, pubKey); } byte[] result = cipher.doFinal(decodeBase64(data)); return (new String(result)); } public enum Mode { SERVER, CLIENT } }
pubkey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALm2mQ3xdwhWN5Q7ac7uFqky7zzpVWImZyfOAi0mUNgRcDciOhml3yJlVc82O8U9DnacWpi2sporixlzMNqqX88CAwEAAQ== prikey: MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAubaZDfF3CFY3lDtpzu4WqTLvPOlVYiZnJ84CLSZQ2BFwNyI6GaXfImVVzzY7xT0OdpxamLaymiuLGXMw2qpfzwIDAQABAkBOt8JKcbZVt03ZrBFeX/cFAwz7EaBaeRKygZTUlHAiFRFSXY7froTKcDtvHXlNVqFE7u3Z4V11wjsNytcFvdexAiEA3NqhTj1RJnxNqcJBpjQJpp/OSnICNo48Sk/1RLCXNJkCIQDXRF56/r0E3xKA2D444z90OpbtnOb5QfylIq5vY5mQpwIgN8PsnvjUmMciRQ8LzI+vMCeBy0JmVKgtiQYPhDyisWECIDG5/mVFIR7V9O1EhqMXg5nyytiazRQ5NQZki4z5ogizAiAoaxxvUvJ2S1yob3ZGEUqjq/W0FUC07bPRQJY6mCuCNQ== pubkey encrypt: BbZoVTpRhkVGGtj7nXZg31Ir3/9oosSbWUhtScuaiPI1fB/vOGIlnPMYk7sXt3y3iA5GtPiV6JyaWw1+ugAk4w== prikey decrypt: 654321 hello world! pubkey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIhtyBCryOFuEiO5x7LQXFPp0hmXv/xPatYTWo5+VZW+QuVcP+Brp52gQsgGDzgtTYHsUFy4ifX4C8HBLWS10IUCAwEAAQ== prikey: MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAiG3IEKvI4W4SI7nHstBcU+nSGZe//E9q1hNajn5Vlb5C5Vw/4GunnaBCyAYPOC1NgexQXLiJ9fgLwcEtZLXQhQIDAQABAkAMC/2dkz2ywkBxzSbYIFP2yO/XeLHoOq8JZj4Z1QgDp99AAH6TVrMNkFOaKUwOdtAOuhcG4aYCaBOipPBFRGQFAiEAw8WjhwkLxCf77M0Hw3RlVwIYxop7kyCOVHh3/Tm74ysCIQCyZnfM+gACafJRiP+zsDCa0PNbEFyCk37yqi8XkB4DDwIhAKzUkU5INSQB7I0cYIsz+bc7eaXlYbz8k8qM49khG/crAiBPp6zqGt4SNdf6S99QDeVF2vItwNptewn9s7sfHDwqRQIgQikpSOWDe/Deabln/E1Iof23z2KnM2lSeJoltXgYiM4= prikey encrypt: E0b3Ms3sjDcEmItK3aMiguu3h+rbkAwZdqIjpUZcyC8NMFcea9xbzHATqRdCrdhYJShusff547Of8FBhpUNpAw== pubkey decrypt: 123456 hello 世界!