암호화 알고리즘 라이브러리는 ES6 및 TypeScript와 호환됩니다
설치:
yarn add crypto-es
node.js 프로젝트에서는 commonjs의 ecmascript modules inesead를 사용하는 것이 좋습니다.
// package.json
{
"type": "module"
}
그런 다음 암호화를 가져올 수 있습니다.
import CryptoES from 'crypto-es';
const rst = CryptoES.MD5("Message").toString();
또는 패키지 무게를 줄이기 위해 기능을 부분적으로 가져옵니다.
import { MD5 } from 'crypto-es/lib/md5.js';
const rst = MD5("Message").toString();
이 라이브러리의 모든 파일에는 자체 .d.ts 파일이 현재 있으므로 TypeScript 프로젝트에서 단일 알고리즘 파일을 부분적으로 가져올 수 있습니다.
cryptojs와 동일합니다
MD5
MD5는 널리 사용되는 해시 기능입니다. 다양한 보안 응용 프로그램에서 사용되었으며 일반적으로 파일의 무결성을 확인하는 데 사용됩니다. 그러나 MD5는 충돌 저항력이 없으며 SSL 인증서 또는이 속성에 의존하는 디지털 서명과 같은 응용 프로그램에는 적합하지 않습니다.
const hash = CryptoES.MD5("Message");
SHA-1
SHA HASH 기능은 NSA (National Security Agency)가 설계했습니다. SHA-1은 기존 SHA HASH 기능 중에서 가장 확립되었으며 다양한 보안 응용 프로그램 및 프로토콜에 사용됩니다. 그러나 새로운 공격이 발견되거나 개선됨에 따라 SHA-1의 충돌 저항은 약화되었습니다.
const hash = CryptoES.SHA1("Message");
SHA-2
SHA-256은 SHA-2 세트의 4 가지 변형 중 하나입니다. SHA-1만큼 널리 사용되지는 않지만 훨씬 더 나은 보안을 제공하는 것으로 보입니다.
const hash = CryptoES.SHA256("Message");
SHA-512는 SHA-256과 크게 동일하지만 32보다는 64 비트 단어로 작동합니다.
const hash = CryptoES.SHA512("Message");
Cryptoes는 또한 SHA-224 및 SHA-384를 지원하며, 이는 각각 동일하지만 잘린 버전의 SHA-256 및 SHA-512입니다.
SHA-3
SHA-3은 64 개의 경쟁 디자인이 평가 된 새로운 암호화 해시 알고리즘을 선택하기위한 5 년 경쟁의 승자입니다.
참고 : 이 구현 SHA-3을 지명했을 때 실수를했습니다. Keccak [C = 2d]로 명명되어야합니다. 각 SHA-3 기능은 Keccak 알고리즘의 인스턴스를 기반으로하며, NIST는 SHA-3 경쟁의 승자로 선택한 NIST는 Keccak과 동일하게 해시를 생성하지 않습니다.
const hash = CryptoES.SHA3("Message");
SHA-3은 224, 256, 384 또는 512 비트 중 하나의 해시 길이를 출력하도록 구성 될 수 있습니다. 기본값은 512 비트입니다.
const hash = CryptoES.SHA3("Message", { outputLength: 512 });
const hash = CryptoES.SHA3("Message", { outputLength: 384 });
const hash = CryptoES.SHA3("Message", { outputLength: 256 });
const hash = CryptoES.SHA3("Message", { outputLength: 224 });
Ripemd-160
const hash = CryptoES.RIPEMD160("Message");
해시 알고리즘은 cryptoes.lib.wordArray의 문자열 또는 인스턴스를 허용합니다. WordArray 객체는 32 비트 단어의 배열을 나타냅니다. 문자열을 전달하면 UTF-8으로 인코딩 된 WordArray로 자동 변환됩니다.
당신이 돌아 오는 해시는 아직 끈이 아닙니다. WordArray 객체입니다. 문자열 컨텍스트에서 WordArray 객체를 사용하면 자동으로 16 진 문자열로 변환됩니다.
const hash = CryptoES.SHA256("Message");
alert(typeof hash); // object
alert(hash); // 2f77668a9dfbf8d5848b9eeb4a7145ca94c6ed9236e4a773f6dcafa5132b2f91
Tostring 메소드를 명시 적으로 호출하고 인코더를 전달하여 WordArray 객체를 다른 형식으로 변환 할 수 있습니다.
const hash = CryptoES.SHA256("Message");
alert(hash.toString(CryptoES.enc.Base64)); // L3dmip37+NWEi57rSnFFypTG7ZI25Kdz9tyvpRMrL5E= alert(hash.toString(CryptoES.enc.Latin1)); // /wf��ûøÕ���ëJqEÊ�Æí�6ä§söܯ¥�+/�
alert(hash.toString(CryptoES.enc.Hex)); // 2f77668a9dfbf8d5848b9eeb4a7145ca94c6ed9236e4a773f6dcafa5132b2f91
const sha256 = CryptoES.algo.SHA256.create();
sha256.update("Message Part 1");
sha256.update("Message Part 2");
sha256.update("Message Part 3");
const hash = sha256.finalize();
Keyed-Hash 메시지 인증 코드 (HMAC)는 암호화 해시 함수를 사용한 메시지 인증 메커니즘입니다.
HMAC는 반복 된 암호화 해시 기능과 함께 사용할 수 있습니다.
const hash = CryptoES.HmacMD5("Message", "Secret Passphrase");
const hash = CryptoES.HmacSHA1("Message", "Secret Passphrase");
const hash = CryptoES.HmacSHA256("Message", "Secret Passphrase");
const hash = CryptoES.HmacSHA512("Message", "Secret Passphrase");
const hmac = CryptoES.algo.HMAC.create(CryptoES.algo.SHA256, "Secret Passphrase");
hmac.update("Message Part 1");
hmac.update("Message Part 2");
hmac.update("Message Part 3");
const hash = hmac.finalize();
PBKDF2는 비밀번호 기반 키 파생 기능입니다. 많은 암호화 응용 프로그램에서 사용자 보안은 궁극적으로 암호에 따라 달라지며 암호는 일반적으로 암호화 키로 직접 사용할 수 없으므로 일부 처리가 필요합니다.
소금은 주어진 암호에 대한 큰 키 세트를 제공하며 반복 카운트는 암호에서 키를 생성하는 데 드는 비용을 증가시켜 공격의 어려움을 증가시킵니다.
const salt = CryptoES.lib.WordArray.random(128/8);
const key128Bits = CryptoES.PBKDF2("Secret Passphrase", salt, { keySize: 128/32 });
const key256Bits = CryptoES.PBKDF2("Secret Passphrase", salt, { keySize: 256/32 });
const key512Bits = CryptoES.PBKDF2("Secret Passphrase", salt, { keySize: 512/32 });
const key512Bits1000Iterations = CryptoES.PBKDF2("Secret Passphrase", salt, { keySize: 512/32, iterations: 1000 });
AES
AES (Advanced Encryption Standard)는 미국 연방 정보 처리 표준 (FIPS)입니다. 15 개의 경쟁 디자인이 평가 된 5 년 과정 후에 선정되었습니다.
const encrypted = CryptoES.AES.encrypt("Message", "Secret Passphrase");
const decrypted = CryptoES.AES.decrypt(encrypted, "Secret Passphrase");
암호화는 AES-128, AES-192 및 AES-256을 지원합니다. 전달한 키의 크기로 변형을 선택합니다. 암호를 사용하면 256 비트 키가 생성됩니다.
Des, Triple des
DES는 이전에 암호화를위한 지배적 인 알고리즘이며 공식 연방 정보 처리 표준 (FIPS)으로 출판되었습니다. DES는 이제 작은 키 크기로 인해 안전하지 않은 것으로 간주됩니다.
const encrypted = CryptoES.DES.encrypt("Message", "Secret Passphrase");
const decrypted = CryptoES.DES.decrypt(encrypted, "Secret Passphrase");
Triple Des는 각 블록에 3 번 DES를 적용하여 키 크기를 증가시킵니다. 알고리즘은이 형식으로 안전하다고 생각됩니다.
const encrypted = CryptoES.TripleDES.encrypt("Message", "Secret Passphrase");
const decrypted = CryptoES.TripleDES.decrypt(encrypted, "Secret Passphrase");
토끼
Rabbit은 고성능 스트림 암호이며 Estream 포트폴리오의 결선 진출 자입니다. 22 개의 디자인이 평가 된 3 1/2 년 프로세스 후 선택된 4 가지 디자인 중 하나입니다.
const encrypted = CryptoES.Rabbit.encrypt("Message", "Secret Passphrase");
const decrypted = CryptoES.Rabbit.decrypt(encrypted, "Secret Passphrase");
RC4, RC4DROP
RC4는 널리 사용되는 스트림 암호입니다. SSL 및 WEP와 같은 인기있는 프로토콜에 사용됩니다. 단순성과 속도로 인해 주목할 만하지 만 알고리즘의 역사는 보안에 대한 자신감을 불러 일으키지 않습니다.
const encrypted = CryptoES.RC4.encrypt("Message", "Secret Passphrase");
const decrypted = CryptoES.RC4.decrypt(encrypted, "Secret Passphrase");
키 스트림의 처음 몇 바이트는 강하게 비 랜덤이며 키에 대한 유출 정보라는 것이 밝혀졌습니다. 우리는 키 스트림의 초기 부분을 폐기 하여이 공격을 방어 할 수 있습니다. 이 수정 된 알고리즘을 전통적으로 RC4 드롭이라고합니다.
기본적으로 192 단어 (768 바이트)가 삭제되지만 여러 단어를 삭제하도록 알고리즘을 구성 할 수 있습니다.
const encrypted = CryptoES.RC4Drop.encrypt("Message", "Secret Passphrase");
const encrypted = CryptoES.RC4Drop.encrypt("Message", "Secret Passphrase", { drop: 3072/4 });
const decrypted = CryptoES.RC4Drop.decrypt(encrypted, "Secret Passphrase", { drop: 3072/4 });
블로우 피쉬
Blowfish는 1993 년 Bruce Schneier가 설계하고 많은 암호 스위트와 암호화 제품에 포함 된 대칭 키 블록 암호입니다. Blowfish는 소프트웨어에서 좋은 암호화 속도를 제공하며 현재까지도 효과적인 암호화가 발견되지 않았습니다. 그러나 고급 암호화 표준 (AES)은 이제 더 많은 관심을 받고 있으며, Schneier는 현대적인 응용 프로그램을 위해 두 가지를 권장합니다.
Schneier는 Blowfish를 일반 목적 알고리즘으로 설계했으며, 노후화 된 DES의 대안으로, 다른 알고리즘과 관련된 문제와 제약이 없음. 당시 Blowfish가 출시되었을 때, 많은 다른 디자인은 독점적이거나 특허에 의해 방해되거나 상업적 또는 정부의 비밀이었습니다. Schneier는 "Blowfish는 명백하지 않으며 모든 국가에서도 그렇게 유지 될 것입니다. 알고리즘은 공개 영역에 배치되며 누구나 자유롭게 사용할 수 있습니다."
디자인의 주목할만한 기능에는 키 의존적 S- 박스와 매우 복잡한 키 일정이 포함됩니다.
const ciphertext = CryptoJS.Blowfish.encrypt(message, key, cfg);
const plaintext = CryptoJS.Blowfish.decrypt(ciphertext, key, cfg);
const key = CryptoES.enc.Hex.parse('000102030405060708090a0b0c0d0e0f');
const iv = CryptoES.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');
const encrypted = CryptoES.AES.encrypt("Message", key, { iv: iv });
const encrypted = CryptoES.AES.encrypt("Message", "Secret Passphrase", { mode: CryptoES.mode.CFB, padding: CryptoES.pad.AnsiX923 });
암호화는 다음 모드를 지원합니다.
암호화는 다음과 같은 패딩 체계를 지원합니다.
일반 텍스트 메시지의 경우 암호 알고리즘은 Cryptoes.lib.wordArray의 문자열 또는 인스턴스를 허용합니다.
열쇠의 경우 문자열을 통과 할 때 암호로 처리되어 실제 키와 IV를 도출하는 데 사용됩니다. 또는 실제 키를 나타내는 WordArray를 전달할 수 있습니다. 실제 키를 통과하면 실제 IV를 통과해야합니다.
암호 텍스트의 경우 암호 알고리즘은 cryptoes.lib.cipherparams의 문자열 또는 인스턴스를 허용합니다. cipherparams 물체는 IV, 소금 및 생 박자 텍스트 자체와 같은 매개 변수 모음을 나타냅니다. 문자열을 전달하면 구성 가능한 형식 전략에 따라 Cipherparams 객체로 자동 변환됩니다.
암호 해독 후 돌아 오는 일반 텍스트는 WordArray 객체입니다. 자세한 내용은 Hashers의 출력을 참조하십시오.
암호화 후 돌아온 암호 텍스트는 아직 문자열이 아닙니다. 암호 파람 대상입니다. cipherparams 객체는 암호화 중에 사용되는 모든 매개 변수에 액세스 할 수 있습니다. 문자열 컨텍스트에서 cipherparams 객체를 사용하면 형식 전략에 따라 문자열로 자동 변환됩니다. 기본값은 OpenSSL 호환 형식입니다.
const encrypted = CryptoES.AES.encrypt("Message", "Secret Passphrase"); alert(encrypted.key); // 74eb593087a982e2a6f5dded54ecd96d1fd0f3d44a58728cdcd40c55227522223
alert(encrypted.iv); // 7781157e2629b094f0e3dd48c4d786115
alert(encrypted.salt); // 7a25f9132ec6a8b34
alert(encrypted.ciphertext); // 73e54154a15d1beeb509d9e12f1e462a0
alert(encrypted); // U2FsdGVkX1+iX5Ey7GqLND5UFUoV0b7rUJ2eEvHkYqA=
다른 암호화 구현과 호환 되려면 자신의 형식을 정의 할 수 있습니다. 형식은 암호 파람 객체와 암호 텍스트 문자열 사이를 변환하는 두 가지 메소드의 객체입니다.
JSON Formatter를 작성하는 방법은 다음과 같습니다.
const JsonFormatter = {
stringify: function (cipherParams) { // create json object with ciphertext
const jsonObj = { ct: cipherParams.ciphertext.toString(CryptoES.enc.Base64) }; // optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return JSON.stringify(jsonObj);
},
parse: function (jsonStr) { // parse json string
const jsonObj = JSON.parse(jsonStr); // extract ciphertext from json object, and create cipher params object
const cipherParams = CryptoES.lib.CipherParams.create(
{ ciphertext: CryptoES.enc.Base64.parse(jsonObj.ct) },
); // optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoES.enc.Hex.parse(jsonObj.iv)
}
if (jsonObj.s) {
cipherParams.salt = CryptoES.enc.Hex.parse(jsonObj.s)
}
return cipherParams;
},
};
const encrypted = CryptoES.AES.encrypt(
"Message",
"Secret Passphrase",
{ format: JsonFormatter },
);
alert(encrypted); // {"ct":"tZ4MsEnfbcDOwqau68aOrQ==","iv":"8a8c8fd8fe33743d3638737ea4a00698","s":"ba06373c8f57179c"}
const decrypted = CryptoES.AES.decrypt(
encrypted,
"Secret Passphrase",
{ format: JsonFormatter },
);
alert(decrypted.toString(CryptoES.enc.Utf8)); // Message
const key = CryptoES.enc.Hex.parse('000102030405060708090a0b0c0d0e0f');
const iv = CryptoES.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');
const aesEncryptor = CryptoES.algo.AES.createEncryptor(key, { iv: iv });
const ciphertextPart1 = aesEncryptor.process("Message Part 1");
const ciphertextPart2 = aesEncryptor.process("Message Part 2");
const ciphertextPart3 = aesEncryptor.process("Message Part 3");
const ciphertextPart4 = aesEncryptor.finalize();
const aesDecryptor = CryptoES.algo.AES.createDecryptor(key, { iv: iv });
const plaintextPart1 = aesDecryptor.process(ciphertextPart1);
const plaintextPart2 = aesDecryptor.process(ciphertextPart2);
const plaintextPart3 = aesDecryptor.process(ciphertextPart3);
const plaintextPart4 = aesDecryptor.process(ciphertextPart4);
const plaintextPart5 = aesDecryptor.finalize();
OpenSSL과 함께
OpenSSL과 암호화 :
openssl enc -aes-256-cbc -in infile -out outfile -pass pass:"Secret Passphrase" -e -base64
암호화로 암호화 :
const decrypted = CryptoES.AES.decrypt(openSSLEncrypted, "Secret Passphrase");
암호화는 Base64, Latin1 또는 Hex와 같은 인코딩 형식에서 WordArray 객체 및 Vera로 변환 할 수 있습니다.
const words = CryptoES.enc.Base64.parse('SGVsbG8sIFdvcmxkIQ==');
const base64 = CryptoES.enc.Base64.stringify(words);
const words = CryptoES.enc.Base64url.parse('SGVsbG8sIFdvcmxkIQ==');
const base64url = CryptoES.enc.Base64.stringify(words);
const words = CryptoES.enc.Latin1.parse('Hello, World!');
const latin1 = CryptoES.enc.Latin1.stringify(words);
const words = CryptoES.enc.Hex.parse('48656c6c6f2c20576f726c6421');
const hex = CryptoES.enc.Hex.stringify(words);
const words = CryptoES.enc.Utf8.parse('?');
const utf8 = CryptoES.enc.Utf8.stringify(words);
const words = CryptoES.enc.Utf16.parse('Hello, World!');
const utf16 = CryptoES.enc.Utf16.stringify(words);
const words = CryptoES.enc.Utf16LE.parse('Hello, World!');
const utf16 = CryptoES.enc.Utf16LE.stringify(words);
WordArray Creator는 암호화 알고리즘이 그들에게 적용될 수 있도록 Arraybuffer 또는 TypedArray를 암송 할 수 있습니다.
const words = CryptoES.lib.WordArray.create(new ArrayBuffer(8));
const rst = CryptoES.AES.encrypt(words, 'Secret Passphrase')
참고 : Arraybuffer는 알고리즘으로 직접 전달할 수 없었으며 먼저 WordArray로 변경해야합니다.
이를 통해 파일 암호화가 더 쉬울 것입니다.
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function () {
const arrayBuffer = reader.result;
const words = CryptoES.lib.WordArray.create(arrayBuffer);
const rst = CryptoES.AES.encrypt(words, 'Secret Passphrase')
...
};
로그 변경
현대의 ecmascript에서 Cryptojs를 리팩토링합니다