Skip to content

Encrypt data with a public key

Asterios Raptis edited this page Dec 27, 2016 · 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.

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