Java RSA 공개 키 암호 화 비밀 키 복호화
package com.lee.utils;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import javax.crypto.Cipher;
public class RSAUtil {
    private final static String PUBLIC_KEY_PATH = "c:/publicKeyFile";
    private final static String PRIVATE_KEY_PATH = "c:/privateKeyFile";
    /**
     *        
     */
    private static void geration(){
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes()); 
            keyPairGenerator.initialize(1024, secureRandom); 
            KeyPair keyPair = keyPairGenerator.genKeyPair(); 
            byte[] publicKeyBytes = keyPair.getPublic().getEncoded(); 
            FileOutputStream fos = new FileOutputStream(PUBLIC_KEY_PATH);  
            fos.write(publicKeyBytes);  
            fos.close(); 
            byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); 
            fos = new FileOutputStream(PRIVATE_KEY_PATH);  
            fos.write(privateKeyBytes);  
            fos.close(); 
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
    }
    
    /**
     *     
     * @param filename
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String filename) throws Exception { 
        File f = new File(filename); 
        FileInputStream fis = new FileInputStream(f);  
        DataInputStream dis = new DataInputStream(fis); 
        byte[] keyBytes = new byte[(int)f.length()];
        dis.readFully(keyBytes);  
        dis.close();
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); 
        KeyFactory kf = KeyFactory.getInstance("RSA");  
        return kf.generatePublic(spec); 
    } 
    
    
    
    /**
     *     
     * @param filename
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String filename)throws Exception { 
        File f = new File(filename); 
        FileInputStream fis = new FileInputStream(f); 
        DataInputStream dis = new DataInputStream(fis); 
        byte[] keyBytes = new byte[(int)f.length()]; 
        dis.readFully(keyBytes); 
        dis.close(); 
        PKCS8EncodedKeySpec spec =new PKCS8EncodedKeySpec(keyBytes); 
        KeyFactory kf = KeyFactory.getInstance("RSA"); 
        return kf.generatePrivate(spec); 
      } 
    public static void main(String[] args) {
        
        geration();
          
        String input = "!!!hello world!!!"; 
        RSAPublicKey pubKey;
        RSAPrivateKey privKey;
        byte[] cipherText;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("RSA");         
            pubKey = (RSAPublicKey) getPublicKey(PUBLIC_KEY_PATH);
            privKey = (RSAPrivateKey) getPrivateKey(PRIVATE_KEY_PATH);
             
            cipher.init(Cipher.ENCRYPT_MODE, pubKey); 
            cipherText = cipher.doFinal(input.getBytes()); 
            //       
            System.out.println("cipher: " + new String(cipherText));         
            //     
            cipher.init(Cipher.DECRYPT_MODE, privKey);  
            byte[] plainText = cipher.doFinal(cipherText); 
            System.out.println("publickey: " + Base64.getEncoder().encode(cipherText));
            System.out.println("plain : " + new String(plainText));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } 
    } 
}이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.