RSA 도구 클래스

9013 단어 rsa
나중에 사용 할 수 있 도록 RSA 도구 클래스 를 기록 하고 암호 화,복호화,서명,키 쌍 생 성 등 방법 을 제공 합 니 다.
import java.io.File;
import java.io.IOException;
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.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Random;

import javax.crypto.Cipher;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.FileUtils;

/**
 * 
 * RSA    。    ,  ,  ,        。
 * 
 */

public final class RSA {
	public static final String RSA_CRYPT_ALGORITHM_NAME = "RSA";

	public static final String RSA_SIGN_ALGORITHM_NAME = "MD5withRSA";
	
	private static final int RSA_KEY_LENGTH = 1024;

	/**
	 * 
	 *      
	 * 
	 * @return KeyPair
	 */

	private static KeyPair generateKeyPair() throws Exception {
		try {
			KeyPairGenerator keyPairGen = KeyPairGenerator
					.getInstance(RSA_CRYPT_ALGORITHM_NAME);
			final int KEY_SIZE = RSA_KEY_LENGTH;//       ,        
			SecureRandom secrand = new SecureRandom();
			//          ,        key,         。。。
			secrand.setSeed(RandomUtils.generateString(RSA_KEY_LENGTH).getBytes()); //         
			keyPairGen.initialize(KEY_SIZE, secrand);
			KeyPair keyPair = keyPairGen.genKeyPair();
			return keyPair;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 *   RSA   ,        
	 * 
	 * @param path
	 */
	public static void keyRSA(String path, boolean isBase64Encode)
			throws Exception {
		KeyPair kp = generateKeyPair();
		//     
		PublicKey pubkey = kp.getPublic();
		//     
		PrivateKey prikey = kp.getPrivate();
		byte[] pubKeyBytes = pubkey.getEncoded();
		byte[] priKeyBytes = prikey.getEncoded();
		if (isBase64Encode) {
			pubKeyBytes = Base64.encode(pubkey.getEncoded()).getBytes();
			priKeyBytes = Base64.encode(prikey.getEncoded()).getBytes();
		}
		//        
		if (StringUtils.isBlank(path)) {
			path = "c:/";
		} else {
			if (!path.endsWith("/")) {
				path = path + "/";
			}
		}
		bytes2File(pubKeyBytes, path + "rsa.publicKey");
		bytes2File(priKeyBytes, path + "rsa.privateKey");

	}

	private static void bytes2File(byte[] keyBytes,
			String filePath) throws IOException {
		File file = new File(filePath);
		if (!file.getParentFile().exists())
			file.getParentFile().mkdirs();
		FileUtils.writeByteArrayToFile(file, keyBytes);
	}
	
	public static PublicKey generateRSAPublicKey(String path,
			boolean base64Encoded) throws Exception {
		return generateRSAPublicKey(getBytes(path), base64Encoded);
	}

	/**
	 *     
	 * 
	 * @param pubKeyString
	 * @return
	 * @throws Exception
	 */
	public static PublicKey generateRSAPublicKey(byte[] pubKeyByte,
			boolean base64Encoded) throws Exception {
		byte[] encodedKey = pubKeyByte;
		//  base64  
		if (base64Encoded) {
			encodedKey = Base64.decode(new String(pubKeyByte));
		}
		X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(encodedKey);
		KeyFactory keyFactory = KeyFactory
				.getInstance(RSA_CRYPT_ALGORITHM_NAME);
		return keyFactory.generatePublic(bobPubKeySpec);
	}
	
	public static PrivateKey generateRSAPrivateKey(String path,
			boolean base64Encoded) throws Exception {
		return generateRSAPrivateKey(getBytes(path), base64Encoded);
	}

	/**
	 *     
	 * 
	 * @param priKeyByte
	 * @return
	 * @throws Exception
	 */
	public static PrivateKey generateRSAPrivateKey(byte[] priKeyByte,
			boolean base64Encoded) throws Exception {
		byte[] encodedKey = priKeyByte;
		//  base64  
		if (base64Encoded) {
			encodedKey = Base64.decode(new String(priKeyByte));
		}
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(encodedKey);
		KeyFactory keyFactory = KeyFactory
				.getInstance(RSA_CRYPT_ALGORITHM_NAME);
		return keyFactory.generatePrivate(priPKCS8);
	}
	
	private static byte[] getBytes(String path) throws IOException {
		File file = new File(path);
		return FileUtils.readFileToByteArray(file);
	}

	/**
	 *   
	 * 
	 * @param key
	 *                 
	 * @param data
	 *                    
	 * @return       
	 */
	public static byte[] encrypt(Key key, byte[] data) throws Exception {
		 if (key != null) {   
	            try {   
	                Cipher cipher = Cipher.getInstance(RSA_CRYPT_ALGORITHM_NAME);   
	                cipher.init(Cipher.ENCRYPT_MODE, key);   
	                return cipher.doFinal(data);   
	            } catch (Exception e) {   
	                e.printStackTrace();   
	            }   
	        }   
	        return null;   
	}

	/**
	 *   
	 * 
	 * @param key
	 *                 
	 * @param raw       
	 * @return       
	 */
	public static byte[] decrypt(Key key, byte[] raw) throws Exception {
		if (key != null) {   
            try {   
                Cipher cipher = Cipher.getInstance(RSA_CRYPT_ALGORITHM_NAME);   
                cipher.init(Cipher.DECRYPT_MODE, key);   
                return cipher.doFinal(raw);   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
  
        return null;   

	}

	/**
	 *   
	 * 
	 * @param privateKey
	 * @param data
	 * @return
	 */
	public static byte[] sign(PrivateKey privateKey, byte[] data)
			throws Exception {
		try {
			//             
			Signature signet = Signature.getInstance(RSA_SIGN_ALGORITHM_NAME);
			signet.initSign(privateKey);
			signet.update(data);
			byte[] signed = signet.sign(); //         
			return signed;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 *         
	 * 
	 * @param publicKey
	 * @param signed
	 * @param orig
	 * @return
	 */
	public static boolean verify(PublicKey publicKey, byte[] signed, byte[] orig)
			throws Exception {
		try {
			Signature signetcheck = Signature
					.getInstance(RSA_SIGN_ALGORITHM_NAME);
			signetcheck.initVerify(publicKey);
			signetcheck.update(orig);
			if (signetcheck.verify(signed)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			throw new Exception(e);
		}

	}

	public static void main(String[] args) throws Exception {
		RSA.keyRSA("D:/12", true);
		
		PublicKey publicKey = RSA.generateRSAPublicKey("D:/12/rsa.publicKey", true);
		PrivateKey privateKey = RSA.generateRSAPrivateKey("D:/12/rsa.privateKey", true);
		
		String str = "rsa test : KKC --> kkc ~ 88";
		byte[] strByte = str.getBytes();
		System.out.println("    :" + str);
		byte[] encrypt = RSA.encrypt(privateKey, strByte);
		byte[] decrypt = RSA.decrypt(publicKey, encrypt);
		System.out.println("      :" + new String(decrypt));
		System.out.println("    、          :" + new String(decrypt).equals(str));
		
		byte[] sign = RSA.sign(privateKey, strByte);
		System.out.println("        :" + RSA.verify(publicKey, sign, strByte));
		System.out.println("         :" + RSA.verify(publicKey, sign, RandomUtils.generateString(20).getBytes()));
	}

}

class RandomUtils { 
	public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	/** 
	 *             (        、  ) 
	 * 
	 * @param length         
	 * @return       
	 */ 
	public static String generateString(int length) { 
		StringBuffer sb = new StringBuffer(); 
		Random random = new Random(); 
		for (int i = 0; i < length; i++) {
			sb.append(allChar.charAt(random.nextInt(allChar.length()))); 
		} 
		return sb.toString(); 
	}
}

 
 

좋은 웹페이지 즐겨찾기