Skip to content

Encrypt data with a public key

Tatjana Kopalova edited this page Jan 8, 2017 · 12 revisions

For encrypt data with a public key that was generated as shown here you can continue and read the generated file with following code:

final File keyPemDir = new File("pem");
final File publickeyPemFile = new File(keyPemDir, "public.pem");	
final PublicKey publicKey = KeyExtensions.readPemPublicKey(publickeyPemFile);

A scenario with the public key is a sign in where the server sends the public key from the username and sends the public key as second step to encode the password from the user so the response will be encoded and not readable to any attacker. An example to do this with javascript is shown here. A full description of the sign in scenario with server to client and back is here

Another javascript library that supports encrypting and decrypting with public and private keys is here

Now we have the public key as a java object that we can use in the crypt model:

final CryptModel<Cipher, PublicKey> encryptModel = 
CryptModel.<Cipher, PublicKey>builder()
	.key(publicKey)
	.algorithm(KeyPairWithModeAndPaddingAlgorithm.
               RSA_ECB_OAEPWithSHA256AndMGF1Padding)
	.build();

This sets the public key and the algorithm that is needed for initialize the cipher object for encryption.

With the crypt model we can instantiate a PublicKeyEncryptor object:

final PublicKeyEncryptor encryptor = new PublicKeyEncryptor(encryptModel);

The final step is to call the encrypt method with the data that shell be encrypted:

final String test = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr";
final byte[] testBytes = test.getBytes("UTF-8");

byte[] encrypted = encryptor.encrypt(testBytes);

In the scenario with the signin you can now send the encrypted data to the server where the server have the private key and can decrypted.

How to decrypt the data with the private key you can find out here