Skip to content
This repository has been archived by the owner on Dec 8, 2024. It is now read-only.

Commit

Permalink
Added PSD Project
Browse files Browse the repository at this point in the history
  • Loading branch information
Radnar9 committed Aug 7, 2023
1 parent 110e9bd commit 1da30c7
Show file tree
Hide file tree
Showing 136 changed files with 5,315 additions and 0 deletions.
108 changes: 108 additions & 0 deletions PSD-Project/code/ClientPSD/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.psd</groupId>
<artifactId>ClientPSD</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>CloudCrypto</groupId>
<artifactId>CloudCrypto</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/CloudCrypto-1.0-SNAPSHOT.jar</systemPath>
</dependency>
<dependency>
<groupId>it.unisa.dia.gas</groupId>
<artifactId>jpbc</artifactId>
<version>2.0.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/jpbc-2.0.0.jar</systemPath>
</dependency>
<dependency>
<groupId>it.unisa.dia.gas</groupId>
<artifactId>jpbc-plaf</artifactId>
<version>2.0.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/jpbc-plaf-2.0.0.jar</systemPath>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.54</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArguments>
<extdirs>${project.basedir}/lib</extdirs>
</compilerArguments>
</configuration>
</plugin>
</plugins>

</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.psd.ClientPSD;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.security.Security;

@SpringBootApplication
@EnableScheduling
public class ClientPSDApplication {

public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
SpringApplication app = new SpringApplication(ClientPSDApplication.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package org.psd.ClientPSD.configuration;

import cn.edu.buaa.crypto.algebra.serparams.PairingKeySerParameter;
import lombok.extern.slf4j.Slf4j;
import org.psd.ClientPSD.model.network.IBEKeySharing;
import org.psd.ClientPSD.model.network.SigninResponse;
import org.psd.ClientPSD.model.network.SignupRequest;
import org.psd.ClientPSD.model.network.SignupResponse;
import org.psd.ClientPSD.service.IBECypherService;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.util.Base64;

@Configuration
@Slf4j
public class AuthenticationSetup {
private RestTemplate restTemplate;
HttpsRestConfig httpsRestConfiguration;
public String refreshToken;
public String accessToken;
Properties properties;

IBECypherService ibeCypherService;
public AuthenticationSetup(Properties properties, HttpsRestConfig httpsRestConfiguration,IBECypherService ibeCypherService) {
this.restTemplate = new RestTemplate();
httpsRestConfiguration.customize(restTemplate);
this.properties = properties;
this.ibeCypherService = ibeCypherService;
register();
login();
test(accessToken);
getIBEKeys();
}


public void register() {
SignupRequest request = new SignupRequest(properties.getUser(), properties.getPassword(),properties.getAddress());
try{
ResponseEntity<?> response = restTemplate.postForEntity(properties.getServerAddress() + "/api/auth/register", request, String.class);
}
catch (Exception e){
}
}

public void getIBEKeys(){
try {
ResponseEntity<IBEKeySharing> response = restTemplate.exchange(properties.getServerAddress() + "/ibe/generate/secretKey", HttpMethod.GET, getHeader(), IBEKeySharing.class);
ibeCypherService.setPublicKey(deSerialize(response.getBody().getPublicKey()));
ibeCypherService.setSecretKey(deSerialize(response.getBody().getSecretKey()));
} catch (Exception e){
log.error(e.getMessage());
}
}

public PairingKeySerParameter deSerialize(String serializedKey){
final byte[] bytes = Base64.getDecoder().decode(serializedKey.getBytes());
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
return (PairingKeySerParameter) in.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}

public void login() {
SignupRequest request = new SignupRequest(properties.getUser(), properties.getPassword(),null);
ResponseEntity<SigninResponse> response = restTemplate.postForEntity(properties.getServerAddress() + "/api/auth/login", request, SigninResponse.class);
if (response.getStatusCode().equals(HttpStatus.OK)) {
refreshToken = response.getBody().getRefreshToken();
accessToken = response.getBody().getAccessToken();
}
}
public void test(String accessTokenParam){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessTokenParam);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(properties.getServerAddress() + "/message", HttpMethod.GET,request, String.class);
log.warn( "\u001b[" // Prefix - see [1]
+ "20" // Brightness
+ ";" // Separator
+ "32" // Red foreground
+ "m" // Suffix
+ "AUTHENTICATION SUCCESSFUL" // the text to output
+ "\u001b[m "); // Prefix + Suffix to reset color);
}

@Scheduled(fixedDelay = 1000 * 60 * 1)
public void refreshToken() {
if(refreshToken == null)
return;
try {
ResponseEntity<SignupResponse> response = restTemplate.exchange(properties.getServerAddress() + "/api/auth/refresh/" + refreshToken, HttpMethod.GET, null, SignupResponse.class);
accessToken = response.getBody().getToken();
}
catch (Exception e){
e.printStackTrace();
register();
login();
}finally {
test(accessToken);
}
}

public HttpEntity<String> getHeader(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);
HttpEntity<String> request = new HttpEntity<String>(headers);
return request;
}
public <T> HttpEntity<T> getHeader(T body){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);
HttpEntity<T> request = new HttpEntity<T>(body,headers);
return request;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package org.psd.ClientPSD.configuration;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
@Configuration
@Slf4j
public class HttpsRestConfig implements RestTemplateCustomizer {
@Value("${trust-store}")
private Resource trustStore;
@Value("${trust-store-password}")
private String trustStorePassword;
String protocol = "TLSv1.2";



@Override
public void customize(RestTemplate restTemplate) {

final SSLContext sslContext;
try {
sslContext = SSLContextBuilder.create()
.loadTrustMaterial(new URL(trustStore.getURL().toString()),
trustStorePassword.toCharArray())
.setProtocol(protocol)
.build();
} catch (Exception e) {
throw new IllegalStateException(
"Failed to setup client SSL context", e
);
} finally {
// it's good security practice to zero out passwords,
// which is why they're char[]
Arrays.fill(trustStorePassword.toCharArray(), (char) 0);
}

final HttpClient httpClient = HttpClientBuilder.create()
.setSSLContext(sslContext).setSSLHostnameVerifier((s, sslSession) -> true).setSSLHostnameVerifier((s, sslSession) -> true)
.build();

final ClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(httpClient);

log.info("Registered SSL truststore {} for client requests",
trustStore);
restTemplate.setRequestFactory(requestFactory);
}

// @Bean
// public RestTemplate generateRestCustomTemplate() {
// HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
// httpRequestFactory.setConnectionRequestTimeout(2000);
// httpRequestFactory.setConnectTimeout(2000);
// httpRequestFactory.setReadTimeout(2000);
// RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
// customize(restTemplate);
// return restTemplate;
// }
@Bean
public RestTemplate generateRestTemplateCustom() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
socketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
httpClient);
requestFactory.setConnectTimeout(2000);
requestFactory.setReadTimeout(2000);
requestFactory.setConnectionRequestTimeout(2000);
return new RestTemplate(requestFactory);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.psd.ClientPSD.configuration;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "app")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Properties {
String serverAddress;
String user;
String password;
String cloudAddress;
String address;
}
Loading

0 comments on commit 1da30c7

Please sign in to comment.