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);
'
728x90
반응형
'Study > Java' 카테고리의 다른 글
[Java] 문자열 치환(Replace) 사용법 & 예제 (0) | 2020.12.24 |
---|---|
Gson을 이용한 json을 객체에 담기 (0) | 2020.11.27 |
[Java] AES256 암호화 및 복호화 (0) | 2020.11.10 |
자바 암호화 sha- 256, sha-512 (0) | 2020.11.10 |
[FCM]파이어베이스에서 안드로이드로 보내기 (0) | 2020.04.29 |
댓글