Skip to content

Commit

Permalink
#36 Refactor: KeyPairGenerator RSA 키페어 생성 & 인증서 정보 암호화/복호화 로직 수정 & PD…
Browse files Browse the repository at this point in the history
…F SHA-256 해시값 저장[박한솔]
  • Loading branch information
pjhcsols committed Nov 1, 2024
1 parent 4c4c949 commit e6c293e
Show file tree
Hide file tree
Showing 13 changed files with 244 additions and 117 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,7 @@ cloud.aws.stack.auto=false
passport.client-secret=
passport.public-key-str=

#RSA ???? ??? ? ???(Public Key)
rsa.public-key=


12 changes: 7 additions & 5 deletions web3-credential-server/build/resources/main/data.sql
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
INSERT INTO users (email, password)
VALUES
('[email protected]', '$2a$10$ENYqGvZ3p6LvtsBnRWINSOJHKlMt1Ykgb3.jCnoKkrhMihviXhkDu'),
('[email protected]', '$2a$10$EXAMPLEHASHFORUSERPASSWORD'),
('3751271433', '$2a$10$ENYqGvZ3p6LvtsBnRWINSOJHKlMt1Ykgb3.jCnoKkrhMihviXhkDu');
('[email protected]', '$2a$10$EXAMPLEHASHFORUSERPASSWORD');

INSERT INTO wallets (user_id, private_key, public_key)
VALUES
(1, 'privateKeyForUser1', 'publicKeyForUser1'),
(2, 'privateKeyForUser2', 'publicKeyForUser2'),
(3, 'privateKeyForUser3', 'publicKeyForUser3');
(1, 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDQ09GHNhajYZvw2Kf9Zn4D75niwEyFZLkCVPiOmUuSZTTx/c/wBOOgNw3Q2Uby0c8ChXdzRkGER+4fdd0J7N4YPVgYc9DANbZKtxow8NWQwmRo/IJxVZQonPVtCjvf5MZeFm10WUctTqtvvrJDFOTWNuqA2PBNTzrIS3DThUkTkX+OSASdlV4UGjBhTcAnUCSykexoARM6Z22tEXwR0lY0st0Uk1/Slfl8XvOx0YFVYHorP4RpkyPy9/ELfxlSvJN6Bs+6KUaLnJIzjIZbfCd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+/5ln10xQybiF+pqUoh5RAsCgYA2V5W2WBmQXzq3tZFXZ6cvF/hWbMxNytsVEtVzd2iy3RVaZYyCH01IRA8RpmCYc1ydh/jasy8L2FctOdhrJ7FGWY9c65V4hEy7XIfjiBY6NJFwHGKQnoilecRTKZK6uPIskOrokZi9MA4zn4HDezaFM3eJ89xZh+Lb7+yjhY/oDw==', 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0NPRhzYWo2Gb8Nin/WZ+A++Z4sBMhWS5AlT4jplLkmU08f3P8ATjoDcN0NlG8tHPAoV3c0ZBhEfuH3XdCezeGD1YGHPQwDW2SrcaMPDVkMJkaPyCcVWUKJz1bQo73+TGXhZtdFlHLU6rb76yQxTk1jbqgNjwTU86yEtw04VJE5F/jkgEnZVeFBowYU3AJ1AkspHsaAETOmdtrRF8EdJWNLLdFJNf0pX5fF7zsdGBVWB6Kz+EaZMj8vfxC38ZUryTegbPuilGi5ySM4yGW3wnb+bhEk65fIPZYT5RrR7ys1S9/23HvEGrik0V9pJvnuQjG7cpXA6QYjYk3bYLDSeKFQIDAQAB'),
(2, 'privateKeyForUser2', 'publicKeyForUser2');

INSERT INTO wallet_pdf_urls (wallet_id, certificate_type, pdf_url)
VALUES
(1, '재학증_1', 'https://basilium-product-bucket.s3.ap-northeast-2.amazonaws.com/1_student_certifications.pdf'),
(1, '여권_1', 'https://s3.ap-northeast-2.amazonaws.com/basilium-product-bucket/1_passport_certification.pdf'),
(2, '재학증_2', null);

INSERT INTO wallet_pdf_hash (wallet_id, certificate_type, pdf_hash)
VALUES
(1, '재학증_1', '82a9ba18e4f8c3bbf64b9500ecd8b7701371db05f32887fc2835447d66cfa8e8'),
(1, '여권_1', 'd2c70bf0b298e152e95649cfeb21c4d9a698b052ee62c0c70d9aa9b4ac6f6325');
15 changes: 12 additions & 3 deletions web3-credential-server/build/resources/main/schema.sql
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
DROP TABLE IF EXISTS wallet_pdf_urls;
DROP TABLE IF EXISTS wallet_pdf_hash;
DROP TABLE IF EXISTS wallets;
DROP TABLE IF EXISTS users;

Expand All @@ -11,8 +12,8 @@ CREATE TABLE users (
CREATE TABLE wallets (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
private_key VARCHAR(255) NOT NULL,
public_key VARCHAR(255),
private_key TEXT NOT NULL, -- TEXT로 변경
public_key TEXT NOT NULL, -- TEXT로 변경
FOREIGN KEY (user_id) REFERENCES users(id)
);

Expand All @@ -22,4 +23,12 @@ CREATE TABLE wallet_pdf_urls (
pdf_url VARCHAR(255),
PRIMARY KEY (wallet_id, certificate_type),
FOREIGN KEY (wallet_id) REFERENCES wallets(id)
);
);

CREATE TABLE wallet_pdf_hash (
wallet_id BIGINT,
certificate_type VARCHAR(255),
pdf_hash VARCHAR(255),
PRIMARY KEY (wallet_id, certificate_type),
FOREIGN KEY (wallet_id) REFERENCES wallets(id)
);
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import web3.service.wallet.WalletService;
import web3.validation.LoginMember;

import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -51,11 +52,12 @@ public ResponseEntity<Wallet> getMyWallet(@LoginMember User loginUser) {
@ApiResponse(responseCode = "400", description = "잘못된 요청")
}
)
public ResponseEntity<Wallet> createWallet(@LoginMember User loginUser) throws WalletAlreadyExistsException {
public ResponseEntity<Wallet> createWallet(@LoginMember User loginUser) throws WalletAlreadyExistsException, NoSuchAlgorithmException {
Wallet wallet = walletService.createWallet(loginUser);
return new ResponseEntity<>(wallet, HttpStatus.CREATED);
}


@PutMapping("/{id}")
@Operation(
summary = "지갑 업데이트",
Expand All @@ -68,9 +70,8 @@ public ResponseEntity<Wallet> createWallet(@LoginMember User loginUser) throws W
public ResponseEntity<Wallet> updateWallet(
@PathVariable Long id,
@RequestParam String privateKey,
@RequestParam String publicKey,
@RequestParam String address) {
Wallet updatedWallet = walletService.updateWallet(id, privateKey, publicKey, address);
@RequestParam String publicKey) {
Wallet updatedWallet = walletService.updateWallet(id, privateKey, publicKey);
return ResponseEntity.ok(updatedWallet);
}

Expand Down
107 changes: 75 additions & 32 deletions web3-credential-server/src/main/java/web3/domain/wallet/Wallet.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Getter;
import web3.domain.user.User;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -25,67 +33,101 @@ public class Wallet {
@Column(name = "pdf_url")
private Map<String, String> pdfUrls = new HashMap<>();

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

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

//공동 인증서 정보 추가?
@ElementCollection
@CollectionTable(name = "wallet_pdf_hash", joinColumns = @JoinColumn(name = "wallet_id"))
@MapKeyColumn(name = "certificate_type")
@Column(name = "pdf_hash")
private Map<String, String> pdfHash = new HashMap<>(); //PDF 해시 비교로직 구성

// 기본 생성자
protected Wallet() {}

// 생성자
public Wallet(User user, String privateKey, String publicKey) {
this.user = user;
this.privateKey = privateKey;
this.publicKey = publicKey;
}

public Wallet(User user, String privateKey) {
this.user = user;
this.privateKey = privateKey;
public Map<String, String> getPdfUrls() {
return pdfUrls;
}

public void updateWallet(String privateKey, String publicKey) {
this.privateKey = privateKey;
this.publicKey = publicKey;
public Long getId() {
return id;
}

public void addToPublicKey(String publicKey){
this.publicKey = publicKey;
public User getUser() {
return user;
}

//key(재학증_1):value(pdfUrl) 로 디비에 저장
public void updatePdfUrl(String certificateType, String pdfUrl) {
this.pdfUrls.put(certificateType, pdfUrl);
public String getPrivateKey() {
return privateKey; // String 반환
}

// 인증서 타입에 따라 PDF URL 가져오기
public String getPdfUrl(String certificateType) {
return this.pdfUrls.get(certificateType);
public String getPublicKey() {
return publicKey; // String 반환
}

public Map<String, String> getPdfUrls() {
return pdfUrls;
public Map<String, String> getPdfHash() {
return pdfHash;
}

public Long getId() {
return id;
@JsonIgnore // 이 메서드는 JSON 직렬화에서 제외합니다.
public PublicKey getPublicKeyDecoder() {
return convertKey(publicKey, true);
}

public User getUser() {
return user;
@JsonIgnore // 이 메서드는 JSON 직렬화에서 제외합니다.
public PrivateKey getPrivateKeyDecoder() {
return convertKey(privateKey, false);
}

public String getPrivateKey() {
return privateKey;
private <T> T convertKey(String key, boolean isPublicKey) {
try {
byte[] keyBytes = Base64.getDecoder().decode(key);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
if (isPublicKey) {
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
return (T) keyFactory.generatePublic(spec);
} else {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
return (T) keyFactory.generatePrivate(spec);
}
} catch (Exception e) {
String keyType = isPublicKey ? "공개키" : "개인키";
throw new RuntimeException(keyType + " 변환 중 오류 발생", e);
}
}

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

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

public void updatePdfHash(String certificateType, String pdfHash) {
this.pdfHash.put(certificateType, pdfHash);
}

// key(재학증_1):value(pdfUrl) 로 디비에 저장
public void updatePdfUrl(String certificateType, String pdfUrl) {
this.pdfUrls.put(certificateType, pdfUrl);
}

// 인증서 타입에 따라 PDF URL 가져오기
public String getPdfUrl(String certificateType) {
return this.pdfUrls.get(certificateType);
}

@Override
Expand All @@ -109,7 +151,8 @@ public String toString() {
", privateKey='" + privateKey + '\'' +
", publicKey='" + publicKey + '\'' +
", pdfUrls=" + pdfUrls +
", pdfHash=" + pdfHash +
'}';
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package web3.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;


@ConfigurationProperties(prefix = "rsa")
public record RsaProperties (
String publicKey //사용안함
){
}
Loading

0 comments on commit e6c293e

Please sign in to comment.