개발Story
Published 2021. 3. 22. 11:17
JAVA(RSA 암호화,복호화) java/암호화

RSA 암호화는 공개키 암호화 방식이다.

 

PRIVATE KEY

PUBLIC KEY 

두 키를 생성하여 . 암호화, 복호화 하는데 사용한다.

 

PUBLIC KEY를 이용하여 암호화하고

PRIVATE KEY를 이용하여 복호화한다.

 

JAVA CODE로 알아보자.

 

우선 util 기능은 이렇게 정의한다.

 

/**

     * 키페어 생성

     */

    static HashMap<String, String> createKeypairAsString() {

        HashMap<String, String> stringKeypair = new HashMap<>();

        try {

            SecureRandom secureRandom = new SecureRandom();

            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

            keyPairGenerator.initialize(KEY_SIZE, secureRandom);

            KeyPair keyPair = keyPairGenerator.genKeyPair();



            PublicKey publicKey = keyPair.getPublic();

            PrivateKey privateKey = keyPair.getPrivate();



            String stringPublicKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());

            String stringPrivateKey = Base64.getEncoder().encodeToString(privateKey.getEncoded());



            stringKeypair.put("publicKey", stringPublicKey);

            stringKeypair.put("privateKey", stringPrivateKey);



        } catch (Exception e) {

            e.printStackTrace();

        }

        return stringKeypair;

    }



    /**

     * 암호화

     */

    static String encode(String plainData, String stringPublicKey) {

        String encryptedData = null;

        try {

            //평문으로 전달받은 공개키를 공개키객체로 만드는 과정

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            byte[] bytePublicKey = Base64.getDecoder().decode(stringPublicKey.getBytes());

            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytePublicKey);

            PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);



            //만들어진 공개키객체를 기반으로 암호화모드로 설정하는 과정

            Cipher cipher = Cipher.getInstance("RSA");

            cipher.init(Cipher.ENCRYPT_MODE, publicKey);



            //평문을 암호화하는 과정

            byte[] byteEncryptedData = cipher.doFinal(plainData.getBytes());

            encryptedData = Base64.getEncoder().encodeToString(byteEncryptedData);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return encryptedData;

    }



    /**

     * 복호화

     */

    static String decode(String encryptedData, String stringPrivateKey) {

        String decryptedData = null;

        try {

            //평문으로 전달받은 개인키를 개인키객체로 만드는 과정

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            byte[] bytePrivateKey = Base64.getDecoder().decode(stringPrivateKey.getBytes());

            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bytePrivateKey);

            PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);



            //만들어진 개인키객체를 기반으로 암호화모드로 설정하는 과정

            Cipher cipher = Cipher.getInstance("RSA");

            cipher.init(Cipher.DECRYPT_MODE, privateKey);



            //암호문을 평문화하는 과정

            byte[] byteEncryptedData = Base64.getDecoder().decode(encryptedData.getBytes());

            byte[] byteDecryptedData = cipher.doFinal(byteEncryptedData);

            decryptedData = new String(byteDecryptedData);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return decryptedData;

    }

 

 

이후 테스트를 하면 된다.

   public static void main(String[] args) {
    	
        HashMap<String, String> rsaKeyPair = createKeypairAsString();
        String publicKey = rsaKeyPair.get("publicKey");
        String privateKey = rsaKeyPair.get("privateKey");

        System.out.println(publicKey+"퍼블릭키");
        System.out.println(privateKey + "프라이빗 키");

        System.out.println("만들어진 공개키:" + publicKey);
        System.out.println("만들어진 개인키:" + privateKey);
        String plainText = "플레인 텍스트";
        //암호화
        String  encryptedText = encode(plainText, publicKey);
        //복호화
        String decryptedText = decode(encryptedText,privateKey);


        System.out.println("평문: " + plainText);
        System.out.println("암호화"+encryptedText);
        System.out.println("복호화"+decryptedText);
        
    }

 끝.

 

 

profile

개발Story

@슬래기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!