How to encrypt and decrypt with RSA public key in Java

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.

Creating an RSA key pair

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.

Export private key in PEM format

"-----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.

Export public key in PEM format

"-----BEGIN PUBLIC KEY-----\r\n" +
encodeBase64(keyPair.getPublic().getEncoded()) + "\r\n" +
"-----END PUBLIC KEY-----\r\n";

Public key cryptography

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.

Complex with private key

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");

Summary

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

How to encrypt and decrypt with RSA public key in Java
Encrypt / decrypt with AES256 in PHP and Java
Encrypt with Java and decrypt with C #
How to call functions in bulk with Java reflection
[Java] How to encrypt with AES encryption with standard library
How to convert A to a and a to A using AND and OR in Java
Create a private key / public key in CentOS8.2 and connect to SSH with VS Code
What happened in "Java 8 to Java 11" and how to build an environment
How to develop and register a Sota app in Java
Differences in how to handle strings between Java and Perl
Encrypt using RSA cryptography in Java
How to name variables in Java
How to concatenate strings in java
How to switch Java version with direnv in terminal on Mac
How to rename a model with foreign key constraints in Rails
[Java] I want to perform distinct with the key in the object
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
How to compile Java with VsCode & Ant
[Java] How to compare with equals method
How to do base conversion in Java
[Java] How to output and write files!
How to implement coding conventions in Java
How to embed Janus Graph in Java
Java to C and C to Java in Android Studio
How to test a private method in Java and partially mock that method
[Personal memo] How to interact with a random number generator in Java
How to SSH into Ubuntu from a terminal with public key authentication
How to make an app with a plugin mechanism [C # and Java]
Java8 / 9 Beginners: Stream API addiction points and how to deal with them
How to create your own annotation in Java and get the value
[Java] How to test for null with JUnit
[Java] How to use FileReader class and BufferedReader class
[Java] How to get and output standard input
How to display a web page in Java
Try to link Ruby and Java with Dapr
How to use Java framework with AWS Lambda! ??
How to get Class from Element in Java
How to use Java API with lambda expression
Check static and public behavior in Java methods
How to get and study java SE8 Gold
How to build API with GraphQL and Rails
[Java] How to substitute Model Mapper in Jackson
How to solve an Expression Problem in Java
How to write Java String # getBytes in Kotlin?
[Java] How to use Calendar class and Date class
How to ZIP a JAVA CSV file and manage it in a Byte array
How to set tabs and spaces to be visible by using the tab key to insert spaces in Java files in Eclipse
How to embed JavaScript variables in HTML with Thymeleaf
How to implement UICollectionView in Swift with code only
How to create a Java environment in just 3 seconds
[Java] How to omit the private constructor in Lombok
How to switch Tomcat context.xml with WTP in Eclipse
[Java] Types of comments and how to write them
[Java] How to omit spring constructor injection with Lombok
How to deploy Java to AWS Lambda with Serverless Framework
How to input / output IBM mainframe files in Java?
How to use Z3 library in Scala with Eclipse
Java memory management and how to read GC Viewer
How to create a data URI (base64) in Java