@hm-soft/dec 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +55 -0
- package/dist/crypto.d.ts +11 -0
- package/dist/crypto.js +202 -0
- package/dist/demo.d.ts +1 -0
- package/dist/demo.js +34 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +14 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute
|
|
108
|
+
must include a readable copy of the attribution notices
|
|
109
|
+
contained within such NOTICE file, excluding those notices
|
|
110
|
+
that do not pertain to any part of the Derivative Works.
|
|
111
|
+
|
|
112
|
+
You may add Your own copyright statement to Your modifications and
|
|
113
|
+
may provide additional or different license terms and conditions
|
|
114
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
115
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
116
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
117
|
+
the conditions stated in this License.
|
|
118
|
+
|
|
119
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
120
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
121
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
122
|
+
this License, without any additional terms or conditions.
|
|
123
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
124
|
+
the terms of any separate license agreement you may have executed
|
|
125
|
+
with Licensor regarding such Contributions.
|
|
126
|
+
|
|
127
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
128
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
129
|
+
except as required for reasonable and customary use in describing the
|
|
130
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
131
|
+
|
|
132
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
133
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
134
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
135
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
136
|
+
implied, including, without limitation, any warranties or conditions
|
|
137
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
138
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
139
|
+
appropriateness of using or redistributing the Work and assume any
|
|
140
|
+
risks associated with Your exercise of permissions under this License.
|
|
141
|
+
|
|
142
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
143
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
144
|
+
unless required by applicable law (such as deliberate and grossly
|
|
145
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
146
|
+
liable to You for damages, including any direct, indirect, special,
|
|
147
|
+
incidental, or consequential damages of any character arising as a
|
|
148
|
+
result of this License or out of the use or inability to use the
|
|
149
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
150
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
151
|
+
other commercial damages or losses), even if such Contributor
|
|
152
|
+
has been advised of the possibility of such damages.
|
|
153
|
+
|
|
154
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
155
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
156
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
157
|
+
or other liability obligations and/or rights consistent with this
|
|
158
|
+
License. However, in accepting such obligations, You may act only
|
|
159
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
160
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
161
|
+
defend, and hold each Contributor harmless for any liability
|
|
162
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
163
|
+
of your accepting any such warranty or additional liability.
|
|
164
|
+
|
|
165
|
+
END OF TERMS AND CONDITIONS
|
|
166
|
+
|
|
167
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
168
|
+
|
|
169
|
+
To apply the Apache License to your work, attach the following
|
|
170
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
171
|
+
replaced with your own identifying information. (Don't include
|
|
172
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
173
|
+
comment syntax for the file format. We also recommend that a
|
|
174
|
+
file or class name and description of purpose be included on the
|
|
175
|
+
same "printed page" as the copyright notice for easier
|
|
176
|
+
identification within third-party archives.
|
|
177
|
+
|
|
178
|
+
Copyright 2026 HMSOFT
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# @hm-soft/dec
|
|
2
|
+
|
|
3
|
+
HMSOFT 복합 복호화 SDK — **읽기(조회) 쪽**.
|
|
4
|
+
[`@hm-soft/enc`](https://www.npmjs.com/package/@hm-soft/enc)가 만든 토큰을 복호화하고, 비밀번호를 검증합니다.
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
토큰 → ③ HMSOFT 셔플 역산 → ② ChaCha20-Poly1305 복호 → ① AES-256-GCM 복호 → 평문
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
암호화 과정의 2겹 AEAD가 복호화 시 **위변조를 자동 검증**합니다.
|
|
11
|
+
|
|
12
|
+
## 설치
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @hm-soft/dec
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## 사용
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { hmsoftDecrypt, verifyPassword, loadKey } from "@hm-soft/dec";
|
|
22
|
+
|
|
23
|
+
const key = loadKey(); // 암호화 때와 동일한 마스터 키
|
|
24
|
+
const row = await db.users.findOne(...);
|
|
25
|
+
|
|
26
|
+
const ssn = hmsoftDecrypt(row.ssn, key); // 토큰 → 평문
|
|
27
|
+
const loginOk = verifyPassword(input, row.pwHash); // 로그인 검증
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### 키 회전 (선택)
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { hmsoftDecrypt, loadKeyring } from "@hm-soft/dec";
|
|
34
|
+
const ring = loadKeyring(); // v1, v2 등 여러 키 보유
|
|
35
|
+
const plain = hmsoftDecrypt(oldToken, ring); // 토큰의 keyId로 알맞은 키 자동 선택
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## API
|
|
39
|
+
|
|
40
|
+
| 함수 | 설명 |
|
|
41
|
+
|------|------|
|
|
42
|
+
| `hmsoftDecrypt(token, key \| keyring)` | 토큰 복호화 → 평문 (변조 시 예외) |
|
|
43
|
+
| `verifyPassword(password, stored)` | scrypt 해시 검증 (상수 시간 비교) |
|
|
44
|
+
| `loadKey(env?)` | 단일 마스터 키(Buffer) 로드 |
|
|
45
|
+
| `loadKeyring(env?)` | 키 회전용 키링 로드 |
|
|
46
|
+
| `tokenKeyId(token)` | 토큰이 어떤 keyId로 암호화됐는지 조회 (마이그레이션용) |
|
|
47
|
+
|
|
48
|
+
## 보안 원칙
|
|
49
|
+
|
|
50
|
+
- 마스터 키가 없으면 복호화는 수학적으로 불가능합니다 (코드 공개돼도 안전).
|
|
51
|
+
- 틀린 키 / 변조된 토큰은 명확히 거부됩니다.
|
|
52
|
+
|
|
53
|
+
## License
|
|
54
|
+
|
|
55
|
+
Apache-2.0
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const KEY_LEN = 32;
|
|
2
|
+
export type Keyring = {
|
|
3
|
+
primaryId: string;
|
|
4
|
+
keys: Record<string, Buffer>;
|
|
5
|
+
};
|
|
6
|
+
export declare function loadKey(env?: NodeJS.ProcessEnv): Buffer;
|
|
7
|
+
export declare function loadKeyring(env?: NodeJS.ProcessEnv): Keyring;
|
|
8
|
+
export declare function tokenKeyId(token: string): string;
|
|
9
|
+
/** 단일 키(Buffer) 또는 키링(Keyring)으로 복호화. 키링이면 토큰의 keyId로 키 선택. */
|
|
10
|
+
export declare function hmsoftDecrypt(token: string, keyOrRing: Buffer | Keyring): string;
|
|
11
|
+
export declare function verifyPassword(password: string, stored: string): boolean;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HM Soft 복합 복호화 코어 (읽기 쪽) — 키 회전(rotation) 지원
|
|
3
|
+
*
|
|
4
|
+
* 토큰의 keyId로 어느 키로 암호화됐는지 알아내, 키링에서 해당 키를 골라 복호화합니다.
|
|
5
|
+
* 따라서 primary 키를 새로 바꿔도, 옛 keyId로 만든 기존 데이터를 계속 읽을 수 있습니다.
|
|
6
|
+
*
|
|
7
|
+
* 토큰 → ③ HMSOFT 셔플 역산 → ② ChaCha20-Poly1305 복호 → ① AES-256-GCM 복호 → 평문
|
|
8
|
+
*/
|
|
9
|
+
import { createDecipheriv, createCipheriv, scryptSync, hkdfSync, timingSafeEqual } from "node:crypto";
|
|
10
|
+
const ALGO_AES = "aes-256-gcm";
|
|
11
|
+
const ALGO_CHACHA = "chacha20-poly1305";
|
|
12
|
+
const AES_IV_LEN = 12;
|
|
13
|
+
const CHACHA_NONCE_LEN = 12;
|
|
14
|
+
const TAG_LEN = 16;
|
|
15
|
+
export const KEY_LEN = 32;
|
|
16
|
+
const TOKEN_PREFIX = "HMSOFT";
|
|
17
|
+
const TOKEN_VERSION = "v1";
|
|
18
|
+
const KEY_ID_RE = /^[A-Za-z0-9_-]+$/;
|
|
19
|
+
const HKDF_SALT = Buffer.from("HMSOFT-SDK-v1");
|
|
20
|
+
const INFO_AES = Buffer.from("HMSOFT/aes-256-gcm");
|
|
21
|
+
const INFO_CHACHA = Buffer.from("HMSOFT/chacha20-poly1305");
|
|
22
|
+
const INFO_PERM = Buffer.from("HMSOFT/permute");
|
|
23
|
+
const INFO_PERM_SEED = Buffer.from("HMSOFT/perm-seed");
|
|
24
|
+
function decodeKey(b64, id) {
|
|
25
|
+
const k = Buffer.from(b64, "base64");
|
|
26
|
+
if (k.length !== KEY_LEN) {
|
|
27
|
+
throw new Error(`키 '${id}' 길이 오류: 32바이트(base64) 필요. (현재 ${k.length}바이트)`);
|
|
28
|
+
}
|
|
29
|
+
return k;
|
|
30
|
+
}
|
|
31
|
+
export function loadKey(env = process.env) {
|
|
32
|
+
const raw = env.HMSOFT_ENC_KEY;
|
|
33
|
+
if (!raw) {
|
|
34
|
+
throw new Error("HMSOFT_ENC_KEY 환경변수가 없습니다. 암호화 때 쓴 키가 필요합니다.");
|
|
35
|
+
}
|
|
36
|
+
return decodeKey(raw, "0");
|
|
37
|
+
}
|
|
38
|
+
export function loadKeyring(env = process.env) {
|
|
39
|
+
const multi = env.HMSOFT_ENC_KEYS;
|
|
40
|
+
if (multi) {
|
|
41
|
+
let obj;
|
|
42
|
+
try {
|
|
43
|
+
obj = JSON.parse(multi);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
throw new Error('HMSOFT_ENC_KEYS는 JSON이어야 합니다. 예: {"v1":"<base64>","v2":"<base64>"}');
|
|
47
|
+
}
|
|
48
|
+
const ids = Object.keys(obj);
|
|
49
|
+
if (ids.length === 0)
|
|
50
|
+
throw new Error("HMSOFT_ENC_KEYS에 키가 하나도 없습니다.");
|
|
51
|
+
const keys = {};
|
|
52
|
+
for (const id of ids) {
|
|
53
|
+
if (!KEY_ID_RE.test(id))
|
|
54
|
+
throw new Error(`잘못된 keyId '${id}' (영숫자, _ , - 만 허용)`);
|
|
55
|
+
keys[id] = decodeKey(obj[id], id);
|
|
56
|
+
}
|
|
57
|
+
let primaryId = env.HMSOFT_ENC_PRIMARY;
|
|
58
|
+
if (!primaryId) {
|
|
59
|
+
if (ids.length === 1)
|
|
60
|
+
primaryId = ids[0];
|
|
61
|
+
else
|
|
62
|
+
throw new Error("키가 여러 개면 HMSOFT_ENC_PRIMARY로 기본 키를 지정하세요.");
|
|
63
|
+
}
|
|
64
|
+
if (!keys[primaryId])
|
|
65
|
+
throw new Error(`HMSOFT_ENC_PRIMARY='${primaryId}' 키가 키링에 없습니다.`);
|
|
66
|
+
return { primaryId, keys };
|
|
67
|
+
}
|
|
68
|
+
const single = env.HMSOFT_ENC_KEY;
|
|
69
|
+
if (!single)
|
|
70
|
+
throw new Error("HMSOFT_ENC_KEYS 또는 HMSOFT_ENC_KEY 환경변수가 필요합니다.");
|
|
71
|
+
return { primaryId: "0", keys: { "0": decodeKey(single, "0") } };
|
|
72
|
+
}
|
|
73
|
+
// ── 도메인 분리 / 셔플 (enc와 동일) ─────────────────────────────────
|
|
74
|
+
function hkdf(master, salt, info) {
|
|
75
|
+
return Buffer.from(hkdfSync("sha256", master, salt, info, KEY_LEN));
|
|
76
|
+
}
|
|
77
|
+
function deriveKeys(master) {
|
|
78
|
+
return {
|
|
79
|
+
kAes: hkdf(master, HKDF_SALT, INFO_AES),
|
|
80
|
+
kChacha: hkdf(master, HKDF_SALT, INFO_CHACHA),
|
|
81
|
+
kPerm: hkdf(master, HKDF_SALT, INFO_PERM),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function keystream(key, len) {
|
|
85
|
+
const iv = Buffer.alloc(16);
|
|
86
|
+
const c = createCipheriv("chacha20", key, iv);
|
|
87
|
+
return Buffer.concat([c.update(Buffer.alloc(len)), c.final()]);
|
|
88
|
+
}
|
|
89
|
+
function permSeed(kPerm, nonce) {
|
|
90
|
+
return Buffer.from(hkdfSync("sha256", kPerm, nonce, INFO_PERM_SEED, KEY_LEN));
|
|
91
|
+
}
|
|
92
|
+
function buildPermutation(seed, n) {
|
|
93
|
+
const perm = Array.from({ length: n }, (_, i) => i);
|
|
94
|
+
if (n <= 1)
|
|
95
|
+
return perm;
|
|
96
|
+
const ks = keystream(seed, n * 4);
|
|
97
|
+
for (let i = n - 1; i > 0; i--) {
|
|
98
|
+
const j = ks.readUInt32LE(i * 4) % (i + 1);
|
|
99
|
+
[perm[i], perm[j]] = [perm[j], perm[i]];
|
|
100
|
+
}
|
|
101
|
+
return perm;
|
|
102
|
+
}
|
|
103
|
+
function unpermute(buf, seed) {
|
|
104
|
+
const perm = buildPermutation(seed, buf.length);
|
|
105
|
+
const out = Buffer.alloc(buf.length);
|
|
106
|
+
for (let k = 0; k < buf.length; k++)
|
|
107
|
+
out[perm[k]] = buf[k];
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
// ── 토큰 파싱: keyId 추출 (4-part 신형 / 3-part 구형 모두 지원) ───────
|
|
111
|
+
function parseToken(token) {
|
|
112
|
+
const parts = token.split(":");
|
|
113
|
+
if (parts[0] !== TOKEN_PREFIX) {
|
|
114
|
+
throw new Error("토큰 형식이 올바르지 않습니다 (HMSOFT 토큰이 아님).");
|
|
115
|
+
}
|
|
116
|
+
if (parts[1] !== TOKEN_VERSION) {
|
|
117
|
+
throw new Error(`지원하지 않는 토큰 버전입니다: ${parts[1]}`);
|
|
118
|
+
}
|
|
119
|
+
let keyId;
|
|
120
|
+
let b64;
|
|
121
|
+
if (parts.length === 4) {
|
|
122
|
+
keyId = parts[2];
|
|
123
|
+
b64 = parts[3];
|
|
124
|
+
}
|
|
125
|
+
else if (parts.length === 3) {
|
|
126
|
+
keyId = "0"; // 구형 토큰 호환
|
|
127
|
+
b64 = parts[2];
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
throw new Error("토큰 형식이 올바르지 않습니다.");
|
|
131
|
+
}
|
|
132
|
+
return { keyId, payload: Buffer.from(b64, "base64url") };
|
|
133
|
+
}
|
|
134
|
+
// ── 어떤 keyId로 토큰이 암호화됐는지 조회 (마이그레이션/감사용) ────────
|
|
135
|
+
export function tokenKeyId(token) {
|
|
136
|
+
return parseToken(token).keyId;
|
|
137
|
+
}
|
|
138
|
+
// ── 메인: HMSOFT 복합 복호화 ───────────────────────────────────────
|
|
139
|
+
/** 단일 키(Buffer) 또는 키링(Keyring)으로 복호화. 키링이면 토큰의 keyId로 키 선택. */
|
|
140
|
+
export function hmsoftDecrypt(token, keyOrRing) {
|
|
141
|
+
const { keyId, payload } = parseToken(token);
|
|
142
|
+
// 키 선택은 try 밖에서 — '키 없음' 같은 명확한 오류를 그대로 전달
|
|
143
|
+
let key;
|
|
144
|
+
if (Buffer.isBuffer(keyOrRing)) {
|
|
145
|
+
key = keyOrRing;
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
key = keyOrRing.keys[keyId];
|
|
149
|
+
if (!key) {
|
|
150
|
+
throw new Error(`키링에 keyId '${keyId}' 키가 없습니다. 이 데이터를 만든 키가 키링에 포함됐는지 확인하세요.`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (key.length !== KEY_LEN)
|
|
154
|
+
throw new Error("키는 32바이트여야 합니다. loadKey()/loadKeyring()을 사용하세요.");
|
|
155
|
+
if (payload.length < CHACHA_NONCE_LEN + TAG_LEN + AES_IV_LEN + TAG_LEN) {
|
|
156
|
+
throw new Error("토큰 데이터가 손상되었습니다 (길이 부족).");
|
|
157
|
+
}
|
|
158
|
+
const { kAes, kChacha, kPerm } = deriveKeys(key);
|
|
159
|
+
try {
|
|
160
|
+
const cNonce = payload.subarray(0, CHACHA_NONCE_LEN);
|
|
161
|
+
const blob2 = payload.subarray(CHACHA_NONCE_LEN);
|
|
162
|
+
// ③ 셔플 역산
|
|
163
|
+
const seed = permSeed(kPerm, cNonce);
|
|
164
|
+
const blob1 = unpermute(blob2, seed);
|
|
165
|
+
// ② ChaCha20-Poly1305 복호
|
|
166
|
+
const chaCt = blob1.subarray(0, blob1.length - TAG_LEN);
|
|
167
|
+
const chaTag = blob1.subarray(blob1.length - TAG_LEN);
|
|
168
|
+
const dc = createDecipheriv(ALGO_CHACHA, kChacha, cNonce, { authTagLength: TAG_LEN });
|
|
169
|
+
dc.setAuthTag(chaTag);
|
|
170
|
+
const blob0 = Buffer.concat([dc.update(chaCt), dc.final()]);
|
|
171
|
+
// ① AES-256-GCM 복호
|
|
172
|
+
const aesIv = blob0.subarray(0, AES_IV_LEN);
|
|
173
|
+
const aesTag = blob0.subarray(AES_IV_LEN, AES_IV_LEN + TAG_LEN);
|
|
174
|
+
const aesCt = blob0.subarray(AES_IV_LEN + TAG_LEN);
|
|
175
|
+
const da = createDecipheriv(ALGO_AES, kAes, aesIv);
|
|
176
|
+
da.setAuthTag(aesTag);
|
|
177
|
+
return Buffer.concat([da.update(aesCt), da.final()]).toString("utf8");
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
throw new Error("복호화 실패: 키가 틀리거나 데이터가 변조되었습니다.");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// ── 비밀번호 검증 ─────────────────────────────────────────────────
|
|
184
|
+
export function verifyPassword(password, stored) {
|
|
185
|
+
const parts = stored.split(":");
|
|
186
|
+
if (parts.length !== 6 || parts[0] !== "scrypt")
|
|
187
|
+
return false;
|
|
188
|
+
const N = Number(parts[1]);
|
|
189
|
+
const r = Number(parts[2]);
|
|
190
|
+
const p = Number(parts[3]);
|
|
191
|
+
if (!N || !r || !p)
|
|
192
|
+
return false;
|
|
193
|
+
const salt = Buffer.from(parts[4], "base64url");
|
|
194
|
+
const expected = Buffer.from(parts[5], "base64url");
|
|
195
|
+
const actual = scryptSync(password, salt, expected.length, {
|
|
196
|
+
N,
|
|
197
|
+
r,
|
|
198
|
+
p,
|
|
199
|
+
maxmem: 128 * N * r * 2,
|
|
200
|
+
});
|
|
201
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
202
|
+
}
|
package/dist/demo.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/demo.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 데모: HMSOFT 복합 복호화 + 변조 탐지 + 비밀번호 검증
|
|
3
|
+
* 실행: (먼저 ../hmsoft-enc 빌드 필요) npm run demo
|
|
4
|
+
*
|
|
5
|
+
* 같은 마스터 키를 공유해야 하므로 enc 패키지의 빌드 결과를 불러와
|
|
6
|
+
* 한 프로세스에서 암호화→복호화를 시연합니다.
|
|
7
|
+
*/
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { hmsoftDecrypt, verifyPassword, loadKey } from "./index.js";
|
|
10
|
+
// @ts-ignore — 데모 전용: 이웃 패키지의 빌드 산출물을 직접 사용
|
|
11
|
+
import { hmsoftEncrypt, hashPassword } from "../../hmsoft-enc/dist/index.js";
|
|
12
|
+
if (!process.env.HMSOFT_ENC_KEY) {
|
|
13
|
+
process.env.HMSOFT_ENC_KEY = randomBytes(32).toString("base64");
|
|
14
|
+
}
|
|
15
|
+
const key = loadKey();
|
|
16
|
+
// 1) 왕복
|
|
17
|
+
const secret = "홍길동 / 901010-1234567";
|
|
18
|
+
const token = hmsoftEncrypt(secret, key);
|
|
19
|
+
console.log("토큰 :", token);
|
|
20
|
+
console.log("복호화 :", hmsoftDecrypt(token, key));
|
|
21
|
+
console.log("→ 왕복 일치:", hmsoftDecrypt(token, key) === secret);
|
|
22
|
+
// 2) 변조 탐지
|
|
23
|
+
const tampered = token.slice(0, -2) + (token.endsWith("AA") ? "BB" : "AA");
|
|
24
|
+
try {
|
|
25
|
+
hmsoftDecrypt(tampered, key);
|
|
26
|
+
console.log("\n[변조 테스트] ❌ 통과되면 안 됨");
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
console.log("\n[변조 테스트] ✅ 변조 감지·거부:", e.message);
|
|
30
|
+
}
|
|
31
|
+
// 3) 비밀번호 검증
|
|
32
|
+
const stored = hashPassword("my-password-123");
|
|
33
|
+
console.log("\n비밀번호 맞음:", verifyPassword("my-password-123", stored));
|
|
34
|
+
console.log("비밀번호 틀림:", verifyPassword("wrong-password", stored));
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmsoft/dec — 읽기(조회) 쪽 SDK
|
|
3
|
+
*
|
|
4
|
+
* // 단일 키
|
|
5
|
+
* import { hmsoftDecrypt, verifyPassword, loadKey } from "@hmsoft/dec";
|
|
6
|
+
* const key = loadKey();
|
|
7
|
+
* const plain = hmsoftDecrypt(row.encrypted, key);
|
|
8
|
+
*
|
|
9
|
+
* // 키 회전(키링) — 토큰의 keyId로 알맞은 키 자동 선택
|
|
10
|
+
* import { hmsoftDecrypt, loadKeyring } from "@hmsoft/dec";
|
|
11
|
+
* const ring = loadKeyring();
|
|
12
|
+
* const plain = hmsoftDecrypt(row.encrypted, ring);
|
|
13
|
+
*/
|
|
14
|
+
export { hmsoftDecrypt, verifyPassword, loadKey, loadKeyring, tokenKeyId, KEY_LEN, } from "./crypto.js";
|
|
15
|
+
export type { Keyring } from "./crypto.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmsoft/dec — 읽기(조회) 쪽 SDK
|
|
3
|
+
*
|
|
4
|
+
* // 단일 키
|
|
5
|
+
* import { hmsoftDecrypt, verifyPassword, loadKey } from "@hmsoft/dec";
|
|
6
|
+
* const key = loadKey();
|
|
7
|
+
* const plain = hmsoftDecrypt(row.encrypted, key);
|
|
8
|
+
*
|
|
9
|
+
* // 키 회전(키링) — 토큰의 keyId로 알맞은 키 자동 선택
|
|
10
|
+
* import { hmsoftDecrypt, loadKeyring } from "@hmsoft/dec";
|
|
11
|
+
* const ring = loadKeyring();
|
|
12
|
+
* const plain = hmsoftDecrypt(row.encrypted, ring);
|
|
13
|
+
*/
|
|
14
|
+
export { hmsoftDecrypt, verifyPassword, loadKey, loadKeyring, tokenKeyId, KEY_LEN, } from "./crypto.js";
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hm-soft/dec",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "HMSOFT 복합 복호화 SDK (읽기) — AES-256-GCM + ChaCha20-Poly1305 + 키 회전 + 비밀번호 검증",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc",
|
|
21
|
+
"demo": "tsc && node dist/demo.js",
|
|
22
|
+
"prepublishOnly": "npm run build"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"decryption",
|
|
26
|
+
"aes-256-gcm",
|
|
27
|
+
"chacha20-poly1305",
|
|
28
|
+
"crypto",
|
|
29
|
+
"key-rotation",
|
|
30
|
+
"hmsoft",
|
|
31
|
+
"pii"
|
|
32
|
+
],
|
|
33
|
+
"author": "HMSOFT",
|
|
34
|
+
"license": "Apache-2.0",
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=18"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
}
|
|
41
|
+
}
|