본문 바로가기
Study/Java

RSA 암호화, 복호화

by 오늘만 사는 여자 2020. 11. 12.
728x90
반응형

암호화 복호화 소스

public static KeyPair genRSAKeyPair() throws NoSuchAlgorithmException {
		KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
		KeyPair keyPair = gen.genKeyPair();
		return keyPair;
	}

	public static String encryptRSA(String plainText, PublicKey publicKey) throws NoSuchPaddingException,
			NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);

		byte[] bytePlain = cipher.doFinal(plainText.getBytes());
		String encrypted = java.util.Base64.getEncoder().encodeToString(bytePlain);
		return encrypted;

	}

	public static String decryptRSA(String encrypted, PrivateKey privateKey)
			throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
			IllegalBlockSizeException, UnsupportedEncodingException {

		Cipher cipher = Cipher.getInstance("RSA");
		byte[] byteEncrypted = java.util.Base64.getDecoder().decode(encrypted.getBytes());

		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] bytePlain = cipher.doFinal(byteEncrypted);
		String decrypted = new String(bytePlain, "utf-8");
		return decrypted;
	}

 

사용법

KeyPair keyPair = genRSAKeyPair();
		PublicKey publicKey = keyPair.getPublic();
		PrivateKey privateKey = keyPair.getPrivate();

		String str = "hello";

		String encrypted = encryptRSA(str, publicKey);

		System.out.println("encrypted : " + encrypted);
		String decrypted = decryptRSA(encrypted, privateKey);

		System.out.println("decrypted : " + decrypted);

		// 공개키를 Base64 인코딩한 문자일을 만듭니다.

		byte[] bytePublicKey = publicKey.getEncoded();

		String base64PublicKey = java.util.Base64.getEncoder().encodeToString(bytePublicKey);

		System.out.println("Base64 Public Key : " + base64PublicKey);

		// 개인키를 Base64 인코딩한 문자열을 만듭니다.

		byte[] bytePrivateKey = privateKey.getEncoded();

		String base64PrivateKey =  java.util.Base64.getEncoder().encodeToString(bytePrivateKey);

		System.out.println("Base64 Private Key : " + base64PrivateKey);

'

 

참조 : offbyone.tistory.com/346

728x90
반응형

댓글