노드에서 키를 발급받아서 저장해 보도록하자
물론 직전코드였지만 우선 보고 시작
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
},
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
});
const privateKeyObj = crypto.createPrivateKey(privateKey);
const publicKeyObj = crypto.createPublicKey(publicKey);
const privateKeyString = privateKeyObj.export({ type: 'pkcs8', format: 'pem' });
const publicKeyString = publicKeyObj.export({ type: 'spki', format: 'pem' });
const message = 'this is plain Text';
const encrypted = crypto.publicEncrypt(
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256',
},
Buffer.from(message, 'utf8')
);
const ecnrypted 가 암호화된 값이다.
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'username',
password : 'password',
database : 'rsatest'
});
connection.connect();
mysql 에 저장해 본다.
app.post('/save/key', async (req, res) => {
let public = Buffer.from(publicKeyString, "utf8").toString('base64');
let private = Buffer.from(privateKeyString, "utf8").toString('base64');
let enc_text = Buffer.from(encrypted, "utf8").toString('base64');
const jsonResult = {
publicKey : public,
privateKey : private,
encrypted : enc_text
}
connection.query(`insert into rsaTable (PRIVATE_KEY, PUBLIC_KEY, ENC_TEXT) VALUES ('${public}', '${private}', '${enc_text}' )`)
res.send(jsonResult).status(200);
});
보면 Buffer 어쩌고 코드가 있는데 이렇게 해주지 않으면 다음과 같은 값들이 날라온다.
enctypted 값만 봐도 문제가 있음을 알수 있다.
값 그대로 들어가게 되는데 publicKey와 privateKey는 굳이 Buffer를 해주지 않고 넣어줘도 되는데 같이 하고 java에서 디코딩해서 사용하기로 한다.
이제야 좀 정상적으로 값이 나온것 같다.
-------------------------------------------
JAVA로 넘어와서
@org.springframework.stereotype.Repository
public interface Repository extends JpaRepository<Entity, Long> {
@Query(value = "select * from rsaTable", nativeQuery = true)
List<Entity> findEntity();
}
@GetMapping("/getENC")
public void test(){
dbConfig.getENC();
}
호출해 보도록하자.
(idx=1, PRIVATE_KEY=LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0.........
정상적으로 잘 넘어온다.
바로 이어서 해야하는데 .. 회사다니면서 블로그 쓰는게 여간 어려운게 아니네여..
다음 포스팅으로
JAVA에서 저 값들을 어떻게 다시 JAVA에서 사용할 수 있는 PRIVATE_KEY, PUBLIC_KEY로 재탄생 시키는지 확인해보도록 하겠습니다.
댓글 영역