crypto.getDiffieHellman() 메서드는 미리 정의된(pre-defined) Diffie-Hellman 그룹을 기반으로 키 교환 객체를 생성할 때 사용됩니다. Node.js에서 지원하는 대표적인 Diffie-Hellman 그룹으로는 modp1, modp2, modp5, modp14, modp16, modp17 등이 있습니다.
이 메서드의 가장 큰 장점은 통신 당사자들이 그룹 모듈러스(group modulus)를 직접 생성하거나 서로 교환할 필요가 없다는 점입니다. 이미 검증된 표준 그룹을 사용하기 때문에 불필요한 연산 과정을 생략할 수 있으며, 그만큼 처리 시간을 절약할 수 있습니다.
문법(Syntax)
crypto.getDiffieHellman(groupName)
매개변수(Parameters)
groupName – 사용할 Diffie-Hellman 그룹의 이름을 문자열(string) 타입으로 전달합니다. 예:
'modp1','modp14'
예제 1: 동일한 그룹으로 키 교환하기
먼저 getDiffieHellman.js라는 이름의 파일을 생성하고 아래 코드를 복사해 넣습니다. 이후 다음 명령어로 코드를 실행할 수 있습니다.
node getDiffieHellman.js
getDiffieHellman.js
// crypto.getDiffieHellman() 데모 예제
// crypto 모듈 임포트
const crypto = require('crypto');
// 동일한 그룹('modp1')으로 서버와 클라이언트 객체 생성
const server = crypto.getDiffieHellman('modp1');
const client = crypto.getDiffieHellman('modp1');
// DiffieHellman 객체 정보 출력
console.log(server);
console.log(client);
// 공개키와 개인키 생성
server.generateKeys();
client.generateKeys();
// 상대방의 공개키를 이용해 공유 비밀키 계산
const serverSecret = server.computeSecret(client.getPublicKey(), null, 'hex');
const clientSecret = client.computeSecret(server.getPublicKey(), null, 'hex');
/* 두 비밀키는 반드시 동일해야 함 */
console.log(serverSecret === clientSecret);실행 결과
C:\home\node>> node getDiffieHellman.js
DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 }
DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 }
true위 결과에서 true가 출력된 것을 확인할 수 있습니다. 이는 서버와 클라이언트가 동일한 그룹(modp1)을 사용했기 때문에 양쪽에서 계산한 공유 비밀키가 일치한다는 의미입니다. 이것이 바로 Diffie-Hellman 키 교환 방식의 핵심 원리입니다.
예제 2: 서로 다른 그룹을 사용할 경우
이번에는 두 객체가 서로 다른 그룹(modp17과 modp14)을 사용하면 어떻게 되는지 살펴보겠습니다.
// crypto.getDiffieHellman() 데모 예제
// crypto 모듈 임포트
const crypto = require('crypto');
// 서로 다른 그룹으로 객체 생성
const dh1 = crypto.getDiffieHellman('modp17');
const dh2 = crypto.getDiffieHellman('modp14');
// 공개키와 개인키 생성
dh1.generateKeys();
dh2.generateKeys();
// 상대방의 공개키를 이용해 공유 비밀키 계산 시도
const dh1Key = dh1.computeSecret(dh2.getPublicKey(), null, 'hex');
const dh2Key = dh2.computeSecret(dh1.getPublicKey(), null, 'hex');
console.log(dh1Key === dh2Key);실행 결과
C:\home\node>> node getDiffieHellman.js
internal/crypto/diffiehellman.js:102
const ret = this._handle.computeSecret(toBuf(key, inEnc));
^
Error: Supplied key is too large
at DiffieHellmanGroup.dhComputeSecret [as computeSecret]
(internal/crypto/diffiehellman.js:102:28)
at Object.<anonymous> (/home/node/test/getDiffieHellman.js:15:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
...주의 사항
두 번째 예제에서 Error: Supplied key is too large 오류가 발생했습니다. 그 이유는 modp14와 modp17이 서로 다른 크기의 소수(prime)를 사용하는 그룹이기 때문입니다. 한쪽 그룹에서 생성된 공개키가 다른 쪽 그룹의 허용 범위를 초과하게 되면 위와 같은 오류가 발생합니다.
따라서 Diffie-Hellman 키 교환을 수행할 때는 통신 당사자 모두 반드시 동일한 그룹 이름을 사용해야 합니다. 이 점만 유의하면 crypto.getDiffieHellman() 메서드를 통해 안전하고 효율적으로 공유 비밀키를 생성할 수 있습니다.