[JAVA] Create an RSA encryption-enabled JSON API with wicket

environment

background

I want to communicate using JSON on the wicket page! By the way, with an encrypted request ...

Request with jsencrypt for RSA encryption

Set the public key to pubKey.

myjsencrypt.js


my.jsencrypt = {
        pubKey: '-----BEGIN PUBLIC KEY-----\
Public key content
-----END PUBLIC KEY-----\
'

Initialize.

myjsencrypt.js


        // encryption setting
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(my.jsencrypt.pubKey);

Throw a request.

myjsencrypt.js


        // request
        var xhr = new XMLHttpRequest();
        xhr.open("POST",Destination URL, true);
        xhr.setRequestHeader("content-type", "application/json");
        xhr.send( encrypt.encrypt(JSON.stringify(data)) );

Library for json

There seem to be various things, but jackson seemed to be good, so I tried using it. It's actually easy to use. Just set the installation in pom.xml.

pom.xml


		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.9.2</version>
		</dependency>

Page processing with Wicket

Get the request and make it a parameter. For RSAUtil, refer to RSA Encryption / Decryption with java 8.

MyJsonPage.java



		RequestCycle requestCycle = getRequestCycle();
		final WebRequest webRequest = (WebRequest) getRequest();
		final HttpServletRequest rawRequest = (HttpServletRequest) webRequest.getContainerRequest();

		BufferedReader br = null;
		JsonFactory jsonFactory = new JsonFactory();
		ObjectMapper jsonMapper = new ObjectMapper(jsonFactory);

		// <Parameter name,value>Make a Map of
		TypeReference<ConcurrentHashMap<String,String>> typeRef = new TypeReference<ConcurrentHashMap<String,String>>(){};

		try {
			StringBuffer sb = new StringBuffer();
			br = rawRequest.getReader();

			for (String line = br.readLine(); line != null; line = br.readLine()) {
				sb.append(line);
			}

			// decrypt RSA input
			PrivateKey privKey = RSAUtil.readPrvateKeyFromPem(Private key file);
			String decrypted = RSAUtil.decryptWithPrivateKey(sb.toString(), privKey);

			// decrypted params to json map
			inputJsonMap = jsonMapper.readValue(decrypted, typeRef);

		} catch (Exception e) {
			/*Error handling*/
		}

Now that the parameters have been obtained, process on this page ...

Prepare a method for setting Content-Type.

MyJsonPage.java


	// Set content-type
	protected String getContentType() {
		final String encoding = getApplication().getRequestCycleSettings().getResponseRequestEncoding();
		return "application/json; charset=" + encoding;
	}

Returns JSON for the result.

MyJsonPage.java


		// build JSON response
		try {
			jsonResponse = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(returnObject);
		} catch (JsonProcessingException e) {
			/*Error handling*/
		}

		requestCycle.scheduleRequestHandlerAfterCurrent(
				new ResourceStreamRequestHandler(
					new StringResourceStream(jsonResponse)	) {

					@Override
					public void respond(IRequestCycle requestCycle) {
						((WebResponse) requestCycle.getResponse()).setContentType(getContentType());
						super.respond(requestCycle);
					}
				}
				);

It's convenient because it converts from Object to JSON. PrettyPrinter is included because it is easy to see.

that's all. Thank you for your hard work!

Recommended Posts

Create an RSA encryption-enabled JSON API with wicket
Create an immutable class with JAVA
Create an app with Spring Boot 2
Create an excel file with poi
Create an easy-to-extend Stream API alternative
Create an app with Spring Boot
Let's create an instance with .new yourself. .. ..
Create an infinite scroll with Infinite Scroll and kaminari
[Java] Create an executable module with Gradle
Create a GUI JSON Viewer with Ruby/GTK3
Create an or search function with Ransack.
Nuxt.js × Create an application in Rails API mode
Create cool API specifications with Micronaut + Swagger UI
Create an EC site with Rails5 ⑤ ~ Customer model ~
Create an Annotator that uses kuromoji with NLP4J [007]
[Swift] Create an image selection UI with PhotoKit
Create a web api server with spring boot
Create an EC site with Rails 5 ⑩ ~ Create an order function ~
Diffed with JSON
I created an api domain with Spring Framework. Part 2
Create an HTTPS file server for development with ring-jetty-adapter
Create an EC site with Rails5 ⑦ ~ Address, Genre model ~
Create an EC site with Rails 5 ⑨ ~ Create a cart function ~
Create an EC site with Rails5 ④ ~ Header and footer ~
Create an E2E test environment with Docker x Cypress
Create a user with an empty password on CentOS7
Create an EC site with Rails5 ⑥ ~ seed data input ~
Create a Service with an empty model Liferay 7.0 / DXP
I created an api domain with Spring Framework. Part 1