I forgot how to encrypt and decrypt using RSA today, so I'll keep it as a memorandum.
In the microservice architecture, there are various methods for passing the user's authentication information, but since the overhead is small and the service side and the caller can reliably authenticate and authorize each other, authentication using the public key I think it is good to encrypt the user information that has already been done.
In the case of RSA, if 1024 bits is specified for the key length, it will be 128 bytes, and since the padding is 11 bytes, the length of the character string that can be encrypted is up to 117 bytes.
It's enough to send the ID of an authenticated user, but be careful about this.
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024); //Specify the RSA key length
KeyPair keyPair = keyGen.generateKeyPair();
KeyPair
contains both the private and public keys.
"-----BEGIN RSA PRIVATE KEY-----\r\n" +
encodeBase64(keyPair.getPrivate().getEncoded()) + "\r\n" +
"-----END RSA PRIVATE KEY-----\r\n";
encodeBase64 (byte [])
is a function that performs Base64 encoding with line breaks for each 64 characters.
"-----BEGIN PUBLIC KEY-----\r\n" +
encodeBase64(keyPair.getPublic().getEncoded()) + "\r\n" +
"-----END PUBLIC KEY-----\r\n";
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
String encrypted = Base64.getEncoder()
.encodeToString(cipher.doFinal(plainText.getBytes("ISO-8859-1")));
Since ECB
is used as the encryption mode, the same ciphertext is always used when the plaintext is the same. If this is unacceptable, it is a good idea to put dummy data in place of IV with random numbers at the beginning of the data.
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());
String plainText = new String(
cipher.doFinal(Base64.getDecoder().decode(encrypted)), "ISO-8859-1");
Not as cumbersome as JWT, RSA encryption, which is commonly used in all language environments, is a real solution for authentication and authorization between microservices.
Recommended Posts