Skip to content

Commit

Permalink
#36 Refactor: privateKey uuid를 넣어서 RSA 암호화 & publicKey 인증서 해시값 저장 [박한솔]
Browse files Browse the repository at this point in the history
  • Loading branch information
pjhcsols committed Nov 1, 2024
1 parent 48f5c7c commit 4c4c949
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 16 deletions.
2 changes: 1 addition & 1 deletion web3-credential-server/build/resources/main/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ CREATE TABLE wallets (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
private_key VARCHAR(255) NOT NULL,
public_key VARCHAR(255) NOT NULL,
public_key VARCHAR(255),
FOREIGN KEY (user_id) REFERENCES users(id)
);

Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,8 @@ public ResponseEntity<Wallet> getMyWallet(@LoginMember User loginUser) {
@ApiResponse(responseCode = "400", description = "잘못된 요청")
}
)
public ResponseEntity<Wallet> createWallet(
@LoginMember User loginUser, // 로그인한 사용자 정보 주입
@RequestParam String privateKey,
@RequestParam String publicKey) throws WalletAlreadyExistsException {
Wallet wallet = walletService.createWallet(loginUser, privateKey, publicKey);
public ResponseEntity<Wallet> createWallet(@LoginMember User loginUser) throws WalletAlreadyExistsException {
Wallet wallet = walletService.createWallet(loginUser);
return new ResponseEntity<>(wallet, HttpStatus.CREATED);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package web3.domain.wallet;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import web3.domain.user.User;
import java.util.HashMap;
Expand All @@ -26,11 +27,12 @@ public class Wallet {

// RSA 암호화를 위한 키
//uuid를 넣어서 RSA 암호화 할때 같이 사용, 메타데이터 업로드 및 가져올때 디코딩
@JsonIgnore
@Column(name = "private_key", nullable = false)
private String privateKey;
private String privateKey; // 메타데이터 디코딩 용

@Column(name = "public_key", nullable = false)
private String publicKey;
@Column(name = "public_key", nullable = true)
private String publicKey; //인증서 해시값 저장

//공동 인증서 정보 추가?

Expand All @@ -42,11 +44,20 @@ public Wallet(User user, String privateKey, String publicKey) {
this.publicKey = publicKey;
}

public Wallet(User user, String privateKey) {
this.user = user;
this.privateKey = privateKey;
}

public void updateWallet(String privateKey, String publicKey) {
this.privateKey = privateKey;
this.publicKey = publicKey;
}

public void addToPublicKey(String publicKey){
this.publicKey = publicKey;
}

//key(재학증_1):value(pdfUrl) 로 디비에 저장
public void updatePdfUrl(String certificateType, String pdfUrl) {
this.pdfUrls.put(certificateType, pdfUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import com.fasterxml.jackson.core.type.TypeReference;
Expand Down Expand Up @@ -64,7 +66,7 @@ public void registerStudentCertification(Long walletId, StudentCertificationDto

try {
String destination = wallet.getPdfUrls().get(metadataKey);
result = handlePdfProcessing(destination, file);
result = handlePdfProcessing(destination, file); //pdf 없으면 생성
} catch (IOException e) {
throw new RuntimeException("파일 처리 중 오류 발생", e);
}
Expand All @@ -73,8 +75,13 @@ public void registerStudentCertification(Long walletId, StudentCertificationDto
metadata.put(metadataKey, metadataString);

log.info("metadata = {}", metadata);

uploadToS3(fileName, metadata, result);

// PDF 파일 해시값 생성
String pdfHash = generatePdfHash(result);
// 지갑에 해시값 추가
wallet.addToPublicKey(pdfHash); // addToPublicKey 메서드는 Wallet 엔티티 내에서 정의

wallet.updatePdfUrl(metadataKey, getPdfUrl(fileName));
walletRepository.saveAndFlush(wallet);
}
Expand Down Expand Up @@ -117,9 +124,12 @@ public void registerPassportCertification(Long walletId, PassportCertificationDt
metadata.put(metadataKey, metadataString);

log.info("metadata = {}", metadata);

// S3에 업로드
uploadToS3(fileName, metadata, result);

// PDF 파일 해시값 생성
String pdfHash = generatePdfHash(result);
// 지갑에 해시값 추가
wallet.addToPublicKey(pdfHash); // addToPublicKey 메서드는 Wallet 엔티티 내에서 정의
wallet.updatePdfUrl(metadataKey, getPdfUrl(fileName));
walletRepository.saveAndFlush(wallet);
}
Expand All @@ -128,6 +138,22 @@ private String generatePassportPdfFileName(Long walletId) {
return walletId + "_passport_certification.pdf";
}

private String generatePdfHash(byte[] fileData) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(fileData);
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("해시 알고리즘을 찾을 수 없습니다.", e);
}
}

//pdf 병합 로직
private byte[] handlePdfProcessing(String destination, MultipartFile file) throws IOException {
byte[] first = (destination != null) ? getBytes(destination) : null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class WalletService {
Expand All @@ -24,12 +25,14 @@ public WalletService(WalletRepository walletRepository) {
}

//지갑 생성
public Wallet createWallet(User user, String privateKey, String publicKey) throws WalletAlreadyExistsException {
public Wallet createWallet(User user) throws WalletAlreadyExistsException {
Optional<Wallet> existingWallet = walletRepository.findByUser(user);
if (existingWallet.isPresent()) {
throw new WalletAlreadyExistsException("User already has a wallet");
}
Wallet wallet = new Wallet(user, privateKey, publicKey);
//pk에 uuid
String privateKey = UUID.randomUUID().toString();
Wallet wallet = new Wallet(user, privateKey);
return walletRepository.save(wallet);
}

Expand Down
2 changes: 1 addition & 1 deletion web3-credential-server/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ CREATE TABLE wallets (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
private_key VARCHAR(255) NOT NULL,
public_key VARCHAR(255) NOT NULL,
public_key VARCHAR(255),
FOREIGN KEY (user_id) REFERENCES users(id)
);

Expand Down

0 comments on commit 4c4c949

Please sign in to comment.