자바 보안 - 비대 칭 암호 화 / 복호화 (소스 코드 구현)

9129 단어 자바Security
암호 화 와 복호화 에는 서로 다른 키 (공개 키 / 비밀 키) 가 사용 되 며 대표 적 으로 RSA, DSA, ElGamal, ECDSA 가 있 습 니 다.비대 칭 암호 화 / 복호화 의 안전성 은 복잡 한 수학 문 제 를 바탕 으로 연산 이 복잡 하고 속도 가 느 리 며 주로 금융, 군사 등 중대 한 기밀 시스템 에 응용 되 는 것 이 특징 이다.
코드 데모:

package com.naxsu.security;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 *   /        
 */
public class SecretKeyTest {
	public static void main(String[] args) throws Exception {
//		 secretEncrypt();
//		 secretDecrypt();

//		 secretEncryptByPass();
//		 secretDecryptByPass();

		publicEncrypt();
		privateDecrypt();
	}
	
	/**
	 *     ,      
	 * @throws Exception
	 */
	private static void secretEncrypt() throws Exception {
		// Cipher:            
		Cipher cipher = Cipher.getInstance("AES");
		//     
		SecretKey key = KeyGenerator.getInstance("AES").generateKey();

		/*
		 *    :   key     ,        ,    ObjectOutputStream.writeObject()
		 *       ,       Serializable             ,Object-->  -->Object
		 */

		//       secret.key   
		saveKey(key, "secret.key");
		//      cipher        
		cipher.init(Cipher.ENCRYPT_MODE, key);
		// cipher.update("aaa".getBytes());
		// cipher.update("aaa".getBytes());
		// byte[] results = cipher.doFinal();

		//  aaa      
		byte[] results = cipher.doFinal("aaa".getBytes());
		System.out.println(new String(results));

		//            data.txt 
		saveData(results, "data.txt");
	}

	/**
	 *     ,             ,         
	 * @throws Exception
	 */
	private static void secretDecrypt() throws Exception {
		Cipher cipher = Cipher.getInstance("AES");
		//        secret.key  
		Key key = readKey("secret.key");
		//      cipher        
		cipher.init(Cipher.DECRYPT_MODE, key);
		//   data.txt  ,        
		byte[] src = readData("data.txt");
		//   
		byte[] result = cipher.doFinal(src);
		System.out.println(new String(result));
	}

	/**
	 *           
	 * @throws Exception
	 */
	private static void secretEncryptByPass() throws Exception {
		Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
		SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
				.generateSecret(new PBEKeySpec("12345678".toCharArray()));
		PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[] { 1,
				2, 3, 4, 5, 6, 7, 8 }, 1000);
		cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);

		byte[] results = cipher.doFinal("aaa".getBytes());
		System.out.println(new String(results));

		saveData(results,"data.txt");
	}

	/**
	 *           
	 * @throws Exception
	 */
	private static void secretDecryptByPass() throws Exception {
		Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
		SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
				.generateSecret(new PBEKeySpec("12345678".toCharArray()));
		PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[] { 1,
				2, 3, 4, 5, 6, 7, 8 }, 1000);
		cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);

		byte[] src = readData("data.txt");

		//   
		byte[] result = cipher.doFinal(src);
		System.out.println(new String(result));
	}

	/**
	 *            
	 * @throws Exception
	 */
	private static void publicEncrypt() throws Exception {
		Cipher cipher = Cipher.getInstance("RSA");
		KeyPairGenerator kPairGenerator = KeyPairGenerator.getInstance("RSA");
		KeyPair keyPair = kPairGenerator.generateKeyPair();
		Key publicKey = keyPair.getPublic();
		Key privateKey = keyPair.getPrivate();
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] result = cipher.doFinal("    ".getBytes("UTF-8"));

		saveKey(privateKey, "secret2.key");
		saveData(result, "data2.txt");
	}

	/**
	 *            
	 * @throws Exception
	 */
	private static void privateDecrypt() throws Exception{
		Cipher cipher = Cipher.getInstance("RSA");
		Key privateKey = readKey("secret2.key");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		
		//  1:
//		byte[] src = readData("data2.txt");
//		byte[] result=cipher.doFinal(src);
//		System.err.println(new String(result,"UTF-8"));
		
		//  2:
//		FileInputStream fis = new FileInputStream("data2.txt");
//		CipherInputStream cis = new CipherInputStream(fis, cipher);
//		//      
//		byte[] buf = new byte[1024];
//		int len = cis.read(buf);
//		System.out.println(new String(buf,0,len,"UTF-8"));
		
		//  3:
		FileInputStream fis = new FileInputStream("data2.txt");
		FileOutputStream fos = new FileOutputStream("result.txt");
		CipherOutputStream cos = new CipherOutputStream(fos, cipher);
		copyStream(fis, cos);
		cos.close();
		fos.close();
		fis.close();
	}

	/**
	 *           
	 * @param is
	 * @param os
	 * @throws IOException
	 */
	private static void copyStream(InputStream is, OutputStream os)
			throws IOException {
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		while (len != -1) {
			os.write(buf, 0, len);
			len = is.read(buf);
		}
	}

	/**
	 *  key      
	 * @param key
	 * @param fileName
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static void saveKey(Key key, String fileName)
			throws FileNotFoundException, IOException {
		FileOutputStream fosKey = new FileOutputStream(fileName);
		ObjectOutputStream oos = new ObjectOutputStream(fosKey);
		oos.writeObject(key);
		oos.close();
		fosKey.close();
	}
	
	/**
	 *             
	 * @param results
	 * @param fileName
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static void saveData(byte[] results, String fileName)
			throws FileNotFoundException, IOException {
		FileOutputStream fosData = new FileOutputStream(fileName);
		fosData.write(results);
		fosData.close();
	}
	
	/**
	 *       key
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private static Key readKey(String fileName) throws FileNotFoundException, IOException,
			ClassNotFoundException {
		FileInputStream fisKey = new FileInputStream(fileName);
		ObjectInputStream oisKey = new ObjectInputStream(fisKey);
		Key key = (Key) oisKey.readObject();
		oisKey.close();
		fisKey.close();
		return key;
	}
	
	/**
	 *            
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static byte[] readData(String fileName) throws FileNotFoundException, IOException {
		FileInputStream fisData = new FileInputStream(fileName);
		//   1:          ,         byte  
		// ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// copyStream(fisData, baos);
		// byte[] src = baos.toByteArray();
		//   2: available()     
		// available():                 (   )        。
		byte[] src = new byte[fisData.available()];
		int len = fisData.read(src);
		int total = 0;
		while (total < src.length) {
			total += len;
			len = fisData.read(src, total, src.length - total);
		}

		fisData.close();
		// baos.close();
		return src;
	}
}


전재 출처 를 밝 혀 주 십시오:http://www.naxsu.com/java-an-quan-fei-dui-cheng-jia-mi-jie-mi/

좋은 웹페이지 즐겨찾기