crypto.createHmac() 메서드는 Hmac 개체를 만든 다음 반환합니다. 이 Hmac은 전달된 알고리즘과 키를 사용합니다. 스트림 동작을 제어하는 데 선택적 옵션이 사용됩니다. 정의된 키는 암호화 HMAC 해시를 생성하는 데 사용되는 HMAC 키입니다.
구문
crypto.createHmac(algorithm, key, [options])
매개변수
위의 매개변수는 다음과 같이 설명됩니다 -
-
알고리즘 – 이 알고리즘은 Hmac 객체를 생성하는 데 사용됩니다. 입력 유형은 문자열입니다.
-
키 – 암호화 Hmac 해시를 생성하는 데 사용되는 Hmac 키입니다.
-
옵션 – 스트림 동작을 제어하는 데 사용할 수 있는 선택적 매개변수입니다.
-
인코딩 – 사용할 문자열 인코딩.
예시
이름이 createHmac.js인 파일을 만들고 아래 코드 스니펫을 복사합니다. 파일을 생성한 후 다음 명령을 사용하여 아래 예와 같이 이 코드를 실행하십시오 -
node createHmac.js
createHmac.js
// crypto.createHmac() demo example
// Importing the crypto module
const crypto = require('crypto');
// Defining the secret key
const secret = 'TutorialsPoint';
// Initializing the createHmac method using secret
const hmacValue = crypto.createHmac('sha256', secret)
// Data to be encoded
.update('Welcome to TutorialsPoint !')
// Defining encoding type
.digest('hex');
// Printing the output
console.log("Hmac value Obtained is: ", hmacValue); 출력
C:\home\node>> node createHmac.js Hmac value Obtained is: dd897f858bad70329fad82087110059f5cb920af2736d96277801f70bd57618e
예시
예를 하나 더 살펴보겠습니다.
// crypto.createHmac() demo example
// Importing the crypto & fs module
const crypto = require('crypto');
const fs = require('fs');
// Getting the current file path
const filename = process.argv[1];
// Creting hmac for current path using secret
const hmac = crypto.createHmac('sha256', "TutorialsPoint");
const input = fs.createReadStream(filename);
input.on('readable', () => {
// Reading single element produced by hmac stream.
const val = input.read();
if (val)
hmac.update(val);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
}); 출력
C:\home\node>> node createHmac.js 0489ce5e4bd940c06253764e03927414f79269fe4f91b1c75184dc074fa86e22 /home/node/test/createHmac .js