Skip to content

Commit

Permalink
Fixed encryption throughout
Browse files Browse the repository at this point in the history
  • Loading branch information
AlistairMRoss committed Oct 11, 2023
1 parent f8687e9 commit 6add8c2
Show file tree
Hide file tree
Showing 19 changed files with 160 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,7 @@
@Slf4j
public class ApplicationConfig {
private final UserRepository repository;
private final AWSSecretService awsSecretService;
private String encryptionKeyString;
private String encryptionIV;
private String decryptionKeyString;
private String decryptionIV;

@Bean
public UserDetailsService userDetailsService(){
return username -> repository.findByEmail(username)
Expand All @@ -60,47 +56,8 @@ public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
@Cacheable(value = {"encryptionKeyString", "encryptionIV"})
public Cipher encryptionCipher() throws Exception {
if(encryptionKeyString == null){
encryptionKeyString = awsSecretService.getEncryptionKey();
}
if(encryptionIV == null){
encryptionIV = awsSecretService.getIV();
}
log.info(encryptionIV);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] encryptionKeyBytes = Base64.getDecoder().decode(encryptionKeyString);
Key encryptionKey = new SecretKeySpec(encryptionKeyBytes, "AES");
byte[] ivBytes = Base64.getDecoder().decode(encryptionIV);
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, ivSpec);
return cipher;
}



@Bean
@Cacheable(value = {"decryptionKeyString", "decryptionIV"})
public Cipher decryptionCipher() throws Exception {
if(decryptionKeyString == null){
decryptionKeyString = awsSecretService.getEncryptionKey();
}
if(decryptionIV == null){
decryptionIV = awsSecretService.getIV();
}

byte[] encryptionKeyBytes = Base64.getDecoder().decode(decryptionKeyString);
Key encryptionKey = new SecretKeySpec(encryptionKeyBytes, "AES");
byte[] ivBytes = Base64.getDecoder().decode(decryptionIV);

IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encryptionKey, ivSpec);
return cipher;
}




Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,14 @@ public ResponseEntity<List<DataScope>> getAllMyDatascopes(){
return ResponseEntity.badRequest().build();
}

@GetMapping("/getDC/{dataScopeId}")
public ResponseEntity<String> getDataCustodian(@PathVariable int dataScopeId){
return ResponseEntity.ok(service.getDataCustodian(dataScopeId));
}

@GetMapping("/getDSUsersEmails/{dataScopeId}")
public ResponseEntity<List<String>> getDSUsersEmails(@PathVariable int dataScopeId){
return ResponseEntity.ok(service.getAllUsersOfDatascope(dataScopeId));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public ResponseEntity<List<Asset>> getAllDevicesForUser() {
}

@GetMapping("/findUsersNotInTask/{task_id}")
public ResponseEntity<List<User>> getAllUsersNotInTask(@PathVariable("task_id") int task_id) {
public ResponseEntity<List<String>> getAllUsersNotInTask(@PathVariable("task_id") int task_id) {
return ResponseEntity.ok(userService.findAllUsersNotInTask(task_id));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class DataScope {
private Date date_captured;
@ManyToOne
@JoinColumn(name = "user_id")
private User data_custodian;
private User dataCustodian;
private String ds_status;

@ManyToMany
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface RoleRepository extends JpaRepository<Role, Integer> {
@Query("SELECT r FROM Role r WHERE r.role_name = :role_name")
Role findByRole_name(@Param("role_name") String role_name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ public interface UserRepository extends JpaRepository<User, Integer> {
@Query("SELECT u.email FROM User u")
List<String> getAllEmails();

@Query("SELECT u FROM User u WHERE u NOT IN (SELECT tu FROM Task t JOIN t.users tu WHERE t.task_id = :taskId)")
List<User> findUsersNotInTask(@Param("taskId") int taskId);
@Query("SELECT u.email FROM User u WHERE u NOT IN (SELECT tu FROM Task t JOIN t.users tu WHERE t.task_id = :taskId)")
List<String> findUsersNotInTask(@Param("taskId") int taskId);

@Query("SELECT u.email FROM User u WHERE u <> :dataCustodian")
List<String> findAllUserNotDataCustodian(@Param("dataCustodian") User dataCustodian);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public class AccessRequestService {

private final EmailService emailService;
private final NotificationsService notificationsService;
private final EncryptionService encryptionService;
public ResponseEntity<String> makeAR(AccessRequestRequest request, User authenticatedUser) {
AccessRequest accessRequest = AccessRequest.builder()
.reason(request.getReason())
Expand Down Expand Up @@ -60,7 +61,7 @@ public ResponseEntity<String> reviewAccessRequest(ReviewRequest reviewRequest) {
log.info(String.valueOf(reviewRequest.isReview()));
if (reviewRequest.isReview()) {
Optional<DataScope> dataScopeOptional = dataScopeRepository.findByDataScopeId(reviewRequest.getDataScope_id());
Optional<User> userOptional = userRepository.findByEmail(reviewRequest.getUser_email());
Optional<User> userOptional = userRepository.findByEmail(encryptionService.encryptString(reviewRequest.getUser_email()));
if (dataScopeOptional.isPresent() && userOptional.isPresent()) {
DataScope dataScope = dataScopeOptional.get();
User user = userOptional.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ public class AssetService {
private final UserRepository userRepository;
private final EmailService emailService;
private final NotificationsService notificationsService;
private final EncryptionService encryptionService;
public List<Asset> getAllAssets() {return assetRepository.findAll();}

public Asset updateAsset(AssetRequest asset) {
if(assetRepository.findByAssetId(asset.getAsset_id()).isPresent()) {
Asset editAsset = assetRepository.findByAssetId(asset.getAsset_id()).get();
User current = userRepository.findByEmail(asset.getCurrent_assignee()).get();
User current = userRepository.findByEmail(encryptionService.encryptString(asset.getCurrent_assignee())).get();
Optional<User> previous = userRepository.findByEmail(asset.getPrevious_assignee());
previous.ifPresent(editAsset::setPrevious_assignee);
editAsset.setAsset_description(asset.getAsset_description());
Expand All @@ -53,12 +54,11 @@ public ResponseEntity<String> makeAsset(AssetRequest request){
.status(request.getStatus())
.availability(request.getAvailability())
.device_type(request.getDevice_type())
//.previous_assignee(request.getPrevious_assignee())
.used(request.getUsed())
.build();

if (request.getCurrent_assignee() != null) {
User user = userRepository.findByEmail(request.getCurrent_assignee()).orElse(null);
User user = userRepository.findByEmail(encryptionService.encryptString(request.getCurrent_assignee())).orElse(null);
if (user != null) {
asset.setCurrent_assignee(user);
emailUser(user.getEmail(), asset.getAsset_name());
Expand Down Expand Up @@ -96,7 +96,7 @@ public List<String> getUnassignedUserEmails(int assetId) {
if(asset.getCurrent_assignee() == null){
return userRepository.getAllEmails();
}else{
return assetRepository.findEmailsOfUsersNotAssignedToAsset(userRepository.findByEmail(asset.getCurrent_assignee().getEmail()).get(), assetId);
return assetRepository.findEmailsOfUsersNotAssignedToAsset(userRepository.findByEmail(encryptionService.encryptString(asset.getCurrent_assignee().getEmail())).get(), assetId);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@
import com.fragile.infosafe.primary.repository.DataScopeRepository;
import com.fragile.infosafe.primary.repository.UserRepository;
import com.fragile.infosafe.primary.requests.DataScopeRequest;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.*;

@Service
@RequiredArgsConstructor
Expand All @@ -24,6 +22,7 @@ public class DataScopeService {
private final UserRepository userRepository;
private final EmailService emailService;
private final NotificationsService notificationsService;
private final EncryptionService encryptionService;

public ResponseEntity<String> makeDs(DataScopeRequest request, User authenticatedUser){
Set<User> dc = new HashSet<>();
Expand All @@ -33,14 +32,14 @@ public ResponseEntity<String> makeDs(DataScopeRequest request, User authenticate
.ds_description(request.getDs_description())
.date_captured(request.getDate_captured())
.ds_status(request.getDs_status())
.data_custodian(authenticatedUser)
.dataCustodian(authenticatedUser)
.users(dc)
.build();
if(!request.getUser_email().isEmpty()){
for(String email : request.getUser_email()){
datascope.getUsers().add(userRepository.findByEmail(email).get());
datascope.getUsers().add(userRepository.findByEmail(encryptionService.encryptString(email)).get());
emailUser(email, datascope.getDs_name());
notificationsService.makeNotification("Assign to Datascope: " + datascope.getDs_name(), userRepository.findByEmail(email).get());
notificationsService.makeNotification("Assign to Datascope: " + datascope.getDs_name(), userRepository.findByEmail(encryptionService.encryptString(email)).get());
}
}
dataScopeRepository.save(datascope);
Expand All @@ -56,7 +55,7 @@ public DataScope updateDataScope(DataScopeRequest request) {
datascope.setDs_name(request.getDs_name());
datascope.setDs_description(request.getDs_description());
datascope.setDs_status(request.getDs_status());
datascope.setData_custodian(userRepository.findById(request.getData_custodian()).get());
datascope.setDataCustodian(userRepository.findById(request.getData_custodian()).get());
return dataScopeRepository.save(datascope);
}
return null;
Expand All @@ -72,6 +71,27 @@ public List<DataScope> getDataScopesNotAssociatedWithUser(User user) {
return dataScopeRepository.findDataScopesNotAssociatedWithUser(user);
}

public List<String> getAllUsersOfDatascope(int ds_id){
Optional<DataScope> entityOptional = dataScopeRepository.findByDataScopeId(ds_id);
if(entityOptional.isPresent()){
DataScope dataScope = entityOptional.get();
List<String> emails = new ArrayList<>();
for(User user : dataScope.getUsers()){
emails.add(encryptionService.decryptString(user.getEmail()));
}
return emails;
}
return null;
}

public String getDataCustodian(int ds_id){
Optional<DataScope> entityOptional = dataScopeRepository.findByDataScopeId(ds_id);
if(entityOptional.isPresent()){
return encryptionService.decryptString(entityOptional.get().getDataCustodian().getEmail());
}
return null;
}

public List<DataScope> getDataScopesByUser(User user) {
return dataScopeRepository.findAllByUsers(user);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public class DeleteService {
private final SupportRequestRepository supportRequestRepository;
private final RiskRepository riskRepository;
private final DataScopeRoleRepository dataScopeRoleRepository;
private final EncryptionService encryptionService;

private final DeletedUserRepository deletedUserRepository;
private final DeletedDataScopeRepository deletedDataScopeRepository;
Expand All @@ -36,7 +37,7 @@ public class DeleteService {
private final DeletedRiskRepository deletedRiskRepository;

public void deleteUserAndSaveToSecondary(String email) {
Optional<User> entityOptional = userRepository.findByEmail(email);
Optional<User> entityOptional = userRepository.findByEmail(encryptionService.encryptString(email));
if (entityOptional.isPresent()) {
log.info("Deleting user");
User entityToDelete = entityOptional.get();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,67 @@
package com.fragile.infosafe.primary.service;

import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

@Service
@RequiredArgsConstructor
public class EncryptionService {
private final Cipher encryptionCipher;
private final Cipher decryptionCipher;
private final AWSSecretService awsSecretService;
private String encryptionKeyString;
private String encryptionIV;
private String decryptionKeyString;
private String decryptionIV;

@Cacheable(value = {"encryptionKeyString", "encryptionIV"})
public Cipher encryptionCipher() throws Exception {
if(encryptionKeyString == null){
encryptionKeyString = awsSecretService.getEncryptionKey();
}
if(encryptionIV == null){
encryptionIV = awsSecretService.getIV();
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] encryptionKeyBytes = Base64.getDecoder().decode(encryptionKeyString);
Key encryptionKey = new SecretKeySpec(encryptionKeyBytes, "AES");
byte[] ivBytes = Base64.getDecoder().decode(encryptionIV);
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, ivSpec);
return cipher;
}


@Cacheable(value = {"decryptionKeyString", "encryptionIV"})
public Cipher decryptionCipher() throws Exception {
if(decryptionKeyString == null){
decryptionKeyString = awsSecretService.getEncryptionKey();
}
if(decryptionIV == null){
decryptionIV = awsSecretService.getIV();
}

byte[] encryptionKeyBytes = Base64.getDecoder().decode(decryptionKeyString);
Key encryptionKey = new SecretKeySpec(encryptionKeyBytes, "AES");
byte[] ivBytes = Base64.getDecoder().decode(decryptionIV);

IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encryptionKey, ivSpec);
return cipher;
}

public String encryptString(String input) {
try {
byte[] inputBytes = input.getBytes("UTF-8");
byte[] encryptedBytes = encryptionCipher.doFinal(inputBytes);
byte[] encryptedBytes = encryptionCipher().doFinal(inputBytes);
return new String(Hex.encode(encryptedBytes));
} catch (Exception e) {
e.printStackTrace();
Expand All @@ -25,7 +71,7 @@ public String encryptString(String input) {
public String decryptString(String encryptedHex) {
try {
byte[] encryptedBytes = Hex.decode(encryptedHex);
byte[] decryptedBytes = decryptionCipher.doFinal(encryptedBytes);
byte[] decryptedBytes = decryptionCipher().doFinal(encryptedBytes);
return new String(decryptedBytes, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
public class NotificationsService {

private final NotificationsRepository notificationsRepository;
private final UserRepository userRepository;

@Scheduled(cron = "0 0 */10 * * *")
public void deleteOldRecords() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public class RiskService {
private final DeleteService deleteService;
private final EmailService emailService;
private final NotificationsService notificationsService;
private final EncryptionService encryptionService;

public List<Risk> getAllRisks() {
return riskRepository.findAll();
Expand All @@ -47,7 +48,7 @@ public ResponseEntity<String> makeRisk(RiskRequest request){
DataScope dataScope = dataScopeRepository.findByDataScopeId(request.getDataScope_id()).get();
risk.setDataScope(dataScope);
for(User user : dataScope.getUsers()){
emailUser(user.getEmail(), risk.getRisk_name(), dataScope.getDs_name());
emailUser(encryptionService.encryptString(user.getEmail()), risk.getRisk_name(), dataScope.getDs_name());
notificationsService.makeNotification("New risk: " + risk.getRisk_name(), user);
}

Expand All @@ -62,7 +63,7 @@ public void reviewRisk(ReviewRiskRequest riskRequest){
if(optionalDataScope.isPresent()) {
DataScope ds = optionalDataScope.get();
for (User user : ds.getUsers()) {
reviewEmail(user.getEmail(), riskRequest.getRisk_name(), ds.getDs_name(), riskRequest.getRisk_status());
reviewEmail(encryptionService.encryptString(user.getEmail()), riskRequest.getRisk_name(), ds.getDs_name(), riskRequest.getRisk_status());
notificationsService.makeNotification("Risk: " + riskRequest.getRisk_name() + "set to " + riskRequest.getRisk_status(), user);
}
if (riskRequest.getRisk_status().equals("Accept") || riskRequest.getRisk_status().equals("Avoid")) {
Expand Down
Loading

0 comments on commit 6add8c2

Please sign in to comment.