RSA 암호 화 자바 버 전 데모
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Scanner;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * 
 * @author leon
 *
 */
class RSAUtils {
  //              
	private static String PUBLIC_KEY_FILE = "PublicKey";
	//              
	private static String PRIVATE_KEY_FILE = "PrivateKey";
	//               
	public static void setKeyPath(String path) {
		if (PUBLIC_KEY_FILE.equals("PublicKey")) {
			PUBLIC_KEY_FILE = path + (path.endsWith("//")?"PublicKey":"/PublicKey");
			PRIVATE_KEY_FILE = path + (path.endsWith("//")?"PrivateKey":"/PrivateKey");
		}
	}
	//      
	private static void createKeyPair() throws Exception {
		//  RSA            keyPairGenerator
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
		//       1024
		keyPairGenerator.initialize(1024);
		//     
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		//    
		Key publicKey = keyPair.getPublic();
		//    
		Key privateKey = keyPair.getPrivate();
		//                 
		ObjectOutputStream oos1 = null;
		ObjectOutputStream oos2 = null;
		try {
			oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
			oos2 = new ObjectOutputStream(
					new FileOutputStream(PRIVATE_KEY_FILE));
			oos1.writeObject(publicKey);
			oos2.writeObject(privateKey);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			oos1.close();
			oos2.close();
		}
	}
    
	//RSA  
	public static String encryptWithRSA(String str) throws Exception {
		createKeyPair();
		Key publicKey = null;
		//          
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
			publicKey = (Key) ois.readObject();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			ois.close();
		}
		//         RSA       cipher。
		Cipher cipher = Cipher.getInstance("RSA");
		//       ,     cipher。
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		//    
		byte[] secret = cipher.doFinal(str.getBytes());
		//  Base64  
		return new BASE64Encoder().encode(secret);
	}
	//RSA  
	public static String decryptWithRSA(String secret) throws Exception {
		Key privateKey;
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
			privateKey = (Key) ois.readObject();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			ois.close();
		}
		Cipher cipher = Cipher.getInstance("RSA");
		//    ,       。
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		//      Base64      ,        
		byte[] b = cipher.doFinal(new BASE64Decoder().decodeBuffer(secret));
		//      
		return new String(b);
	}
}
public class RSA_Demo {
  public static void main(String[] args) throws Exception {
		//          ,  ,       
		//RSAUtils.setKeyPath(str);
		System.out.println("     :");
		Scanner sca = new Scanner(System.in);
		String str =sca.nextLine();
		System.out.println("============================");
		String secret = RSAUtils.encryptWithRSA(str);
		System.out.println("  RSA       :");
		System.out.println(secret);
		System.out.println("============================");
		String original = RSAUtils.decryptWithRSA(secret);
		System.out.println("  RSA       :");
		System.out.println(original);
	}
}이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.