Skip to content

Instantly share code, notes, and snippets.

@timpamungkas
Created April 26, 2022 07:27
Show Gist options
  • Save timpamungkas/73ea229f0f2c225ab16db733b368a3cb to your computer and use it in GitHub Desktop.
Save timpamungkas/73ea229f0f2c225ab16db733b368a3cb to your computer and use it in GitHub Desktop.
SampleAPI for RSA + AES encryption
package com.example.secure;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.ThreadLocalRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
@RestController
@RequestMapping("/api/crypto")
public class CryptographyApi {
@Autowired
private CryptographyService cryptographyService;
@Autowired
private ObjectMapper objectMapper;
private final SecureRandom secureRandom = new SecureRandom();
@GetMapping(value = "/encrypted_string", produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> getEncrypted(@RequestHeader(name = "public-key", required = true) String rsaPublicKey)
throws InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException,
Exception {
var leadSample = Customer.builder().customerId("cust" + RandomStringUtils.randomNumeric(8))
.customerName("Customer name " + ThreadLocalRandom.current().nextInt())
.dateOfBirth(LocalDateTime.now().truncatedTo(ChronoUnit.DAYS)
.minusMonths(ThreadLocalRandom.current().nextInt(12 * 22, 12 * 55)))
.build();
var plainText = objectMapper.writeValueAsString(leadSample);
var salt = Long.toString(secureRandom.nextLong(100000l, 999999999l));
var cipherKey = salt + RandomStringUtils.randomAlphanumeric(32 - salt.length());
// encrypt plain text to AES
var encryptedText = cryptographyService.encryptAES(plainText, cipherKey);
// encrypt AES cipher key (asymmetric RSA via public key)
var rsaCipherKey = cryptographyService.encryptRSA(cipherKey,
cryptographyService.getRSAPublicFromBase64(rsaPublicKey));
return ResponseEntity.ok().header("Encrypted-AES-Key", rsaCipherKey).body(encryptedText);
}
}
@adamsoro0321
Copy link

Hi !
I read your tutorial a lot and it helped me.

But there's something I don't understand, when you pass public-key in requestHeader , I wonder how a client can pass data in the request header.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment