@hm-soft/enc 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 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,68 @@
1
+ # @hm-soft/enc
2
+
3
+ HMSOFT 복합 암호화 SDK — **쓰기(저장) 쪽**.
4
+ 표준 암호 위에 HMSOFT 고유 레이어를 얹은 다층(cascade) 구조로 민감 데이터를 암호화합니다.
5
+
6
+ ```
7
+ 평문
8
+ ① AES-256-GCM ← 절대 방어선 (키 없으면 못 풂)
9
+ ② ChaCha20-Poly1305 ← 2차 표준 암호 (캐스케이드)
10
+ ③ HMSOFT 키 기반 셔플 ← HMSOFT 고유 변환 레이어
11
+ → "HMSOFT:v1:<keyId>:<base64url>" 토큰
12
+ ```
13
+
14
+ 복호화는 짝 패키지 [`@hm-soft/dec`](https://www.npmjs.com/package/@hm-soft/dec)를 사용하세요.
15
+
16
+ ## 설치
17
+
18
+ ```bash
19
+ npm install @hm-soft/enc
20
+ ```
21
+
22
+ ## 사용
23
+
24
+ ```ts
25
+ import { hmsoftEncrypt, hashPassword, loadKey, generateKey } from "@hm-soft/enc";
26
+
27
+ // 1) 마스터 키 한 번 생성 → 환경변수 HMSOFT_ENC_KEY 에 보관
28
+ // node -e "import('@hm-soft/enc').then(m=>console.log(m.generateKey()))"
29
+
30
+ const key = loadKey(); // 환경변수에서 로드
31
+ await db.users.insert({
32
+ ssn: hmsoftEncrypt("901010-1234567", key), // 민감정보 → 암호화
33
+ pwHash: hashPassword(rawPassword), // 비밀번호 → 해싱(복호화 불가)
34
+ });
35
+ ```
36
+
37
+ ### 키 회전 (선택)
38
+
39
+ ```bash
40
+ HMSOFT_ENC_KEYS='{"v1":"<옛키 base64>","v2":"<새키 base64>"}'
41
+ HMSOFT_ENC_PRIMARY=v2
42
+ ```
43
+
44
+ ```ts
45
+ import { hmsoftEncrypt, loadKeyring } from "@hm-soft/enc";
46
+ const ring = loadKeyring();
47
+ const enc = hmsoftEncrypt("민감정보", ring); // 항상 primary 키로 암호화
48
+ ```
49
+
50
+ ## API
51
+
52
+ | 함수 | 설명 |
53
+ |------|------|
54
+ | `hmsoftEncrypt(text, key \| keyring)` | 복합 암호화 → 토큰 문자열 |
55
+ | `hashPassword(password)` | scrypt 단방향 해싱 (복호화 불가) |
56
+ | `loadKey(env?)` | 단일 마스터 키(Buffer) 로드 |
57
+ | `loadKeyring(env?)` | 키 회전용 키링 로드 |
58
+ | `generateKey()` | 새 32바이트 키(base64) 생성 |
59
+
60
+ ## 보안 원칙
61
+
62
+ - 안전성은 **코드가 아니라 키**에서 나옵니다. 소스가 공개돼도 키 없이는 못 풉니다.
63
+ - 마스터 키를 **코드/깃/DB/로그에 절대 넣지 마세요.**
64
+ - 비밀번호는 암호화가 아니라 반드시 `hashPassword()`로 해싱하세요.
65
+
66
+ ## License
67
+
68
+ Apache-2.0
@@ -0,0 +1,27 @@
1
+ export declare const KEY_LEN = 32;
2
+ /** 키링: keyId → 32바이트 키. primaryId가 신규 암호화에 쓰일 기본 키. */
3
+ export type Keyring = {
4
+ primaryId: string;
5
+ keys: Record<string, Buffer>;
6
+ };
7
+ /** 새 32바이트 마스터 키를 base64로 생성. */
8
+ export declare function generateKey(): string;
9
+ /** 단일 키 로드 (회전 불필요한 간단한 경우). 환경변수 HMSOFT_ENC_KEY. */
10
+ export declare function loadKey(env?: NodeJS.ProcessEnv): Buffer;
11
+ /**
12
+ * 키링 로드 (회전 지원).
13
+ * HMSOFT_ENC_KEYS='{"v1":"<base64>","v2":"<base64>"}' ← 여러 키
14
+ * HMSOFT_ENC_PRIMARY=v2 ← 신규 암호화에 쓸 키
15
+ * HMSOFT_ENC_KEYS가 없으면 단일 키(HMSOFT_ENC_KEY)를 keyId "0"으로 사용.
16
+ */
17
+ export declare function loadKeyring(env?: NodeJS.ProcessEnv): Keyring;
18
+ export declare function deriveKeys(master: Buffer): {
19
+ kAes: Buffer<ArrayBufferLike>;
20
+ kChacha: Buffer<ArrayBufferLike>;
21
+ kPerm: Buffer<ArrayBufferLike>;
22
+ };
23
+ export declare function permSeed(kPerm: Buffer, nonce: Buffer): Buffer;
24
+ export declare function buildPermutation(seed: Buffer, n: number): number[];
25
+ /** 단일 키(Buffer) 또는 키링(Keyring)으로 암호화. 키링이면 primary 키를 사용. */
26
+ export declare function hmsoftEncrypt(plaintext: string, keyOrRing: Buffer | Keyring): string;
27
+ export declare function hashPassword(password: string): string;
package/dist/crypto.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * HM Soft 복합 암호화 코어 (쓰기 쪽) — 키 회전(rotation) 지원
3
+ *
4
+ * 구조: 평문
5
+ * ① AES-256-GCM ← 절대 방어선. 키 없으면 수학적으로 못 풂
6
+ * ② ChaCha20-Poly1305 ← 2차 표준 암호 (캐스케이드 / 다층 방어)
7
+ * ③ HMSOFT 키 기반 셔플 ← HMSOFT만의 고유 변환 레이어
8
+ * → "HMSOFT:v1:<keyId>:<base64url>" 토큰
9
+ *
10
+ * keyId로 여러 키를 구분(키링)하므로, 키가 유출돼도 새 키로 무중단 교체할 수 있고
11
+ * 옛 keyId로 암호화된 기존 데이터도 계속 복호화됩니다.
12
+ */
13
+ import { randomBytes, createCipheriv, scryptSync, hkdfSync } from "node:crypto";
14
+ // ── 상수 ──────────────────────────────────────────────────────────
15
+ const ALGO_AES = "aes-256-gcm";
16
+ const ALGO_CHACHA = "chacha20-poly1305";
17
+ const AES_IV_LEN = 12;
18
+ const CHACHA_NONCE_LEN = 12;
19
+ const TAG_LEN = 16;
20
+ export const KEY_LEN = 32;
21
+ const TOKEN_PREFIX = "HMSOFT";
22
+ const TOKEN_VERSION = "v1";
23
+ const KEY_ID_RE = /^[A-Za-z0-9_-]+$/; // keyId는 토큰 구분자(:)를 포함할 수 없음
24
+ const HKDF_SALT = Buffer.from("HMSOFT-SDK-v1");
25
+ const INFO_AES = Buffer.from("HMSOFT/aes-256-gcm");
26
+ const INFO_CHACHA = Buffer.from("HMSOFT/chacha20-poly1305");
27
+ const INFO_PERM = Buffer.from("HMSOFT/permute");
28
+ const INFO_PERM_SEED = Buffer.from("HMSOFT/perm-seed");
29
+ /** 새 32바이트 마스터 키를 base64로 생성. */
30
+ export function generateKey() {
31
+ return randomBytes(KEY_LEN).toString("base64");
32
+ }
33
+ function decodeKey(b64, id) {
34
+ const k = Buffer.from(b64, "base64");
35
+ if (k.length !== KEY_LEN) {
36
+ throw new Error(`키 '${id}' 길이 오류: 32바이트(base64) 필요. (현재 ${k.length}바이트)`);
37
+ }
38
+ return k;
39
+ }
40
+ /** 단일 키 로드 (회전 불필요한 간단한 경우). 환경변수 HMSOFT_ENC_KEY. */
41
+ export function loadKey(env = process.env) {
42
+ const raw = env.HMSOFT_ENC_KEY;
43
+ if (!raw) {
44
+ throw new Error("HMSOFT_ENC_KEY 환경변수가 없습니다. generateKey()로 키를 만들어 설정하세요.");
45
+ }
46
+ return decodeKey(raw, "0");
47
+ }
48
+ /**
49
+ * 키링 로드 (회전 지원).
50
+ * HMSOFT_ENC_KEYS='{"v1":"<base64>","v2":"<base64>"}' ← 여러 키
51
+ * HMSOFT_ENC_PRIMARY=v2 ← 신규 암호화에 쓸 키
52
+ * HMSOFT_ENC_KEYS가 없으면 단일 키(HMSOFT_ENC_KEY)를 keyId "0"으로 사용.
53
+ */
54
+ export function loadKeyring(env = process.env) {
55
+ const multi = env.HMSOFT_ENC_KEYS;
56
+ if (multi) {
57
+ let obj;
58
+ try {
59
+ obj = JSON.parse(multi);
60
+ }
61
+ catch {
62
+ throw new Error('HMSOFT_ENC_KEYS는 JSON이어야 합니다. 예: {"v1":"<base64>","v2":"<base64>"}');
63
+ }
64
+ const ids = Object.keys(obj);
65
+ if (ids.length === 0)
66
+ throw new Error("HMSOFT_ENC_KEYS에 키가 하나도 없습니다.");
67
+ const keys = {};
68
+ for (const id of ids) {
69
+ if (!KEY_ID_RE.test(id))
70
+ throw new Error(`잘못된 keyId '${id}' (영숫자, _ , - 만 허용)`);
71
+ keys[id] = decodeKey(obj[id], id);
72
+ }
73
+ let primaryId = env.HMSOFT_ENC_PRIMARY;
74
+ if (!primaryId) {
75
+ if (ids.length === 1)
76
+ primaryId = ids[0];
77
+ else
78
+ throw new Error("키가 여러 개면 HMSOFT_ENC_PRIMARY로 기본(신규 암호화) 키를 지정하세요.");
79
+ }
80
+ if (!keys[primaryId])
81
+ throw new Error(`HMSOFT_ENC_PRIMARY='${primaryId}' 키가 키링에 없습니다.`);
82
+ return { primaryId, keys };
83
+ }
84
+ // 단일 키 호환
85
+ const single = env.HMSOFT_ENC_KEY;
86
+ if (!single) {
87
+ throw new Error("HMSOFT_ENC_KEYS 또는 HMSOFT_ENC_KEY 환경변수가 필요합니다.");
88
+ }
89
+ return { primaryId: "0", keys: { "0": decodeKey(single, "0") } };
90
+ }
91
+ // ── HMSOFT 도메인 분리: 마스터 키 → 레이어별 서브키 ─────────────────
92
+ function hkdf(master, salt, info) {
93
+ return Buffer.from(hkdfSync("sha256", master, salt, info, KEY_LEN));
94
+ }
95
+ export function deriveKeys(master) {
96
+ return {
97
+ kAes: hkdf(master, HKDF_SALT, INFO_AES),
98
+ kChacha: hkdf(master, HKDF_SALT, INFO_CHACHA),
99
+ kPerm: hkdf(master, HKDF_SALT, INFO_PERM),
100
+ };
101
+ }
102
+ // ── HMSOFT 셔플 레이어 ─────────────────────────────────────────────
103
+ function keystream(key, len) {
104
+ const iv = Buffer.alloc(16);
105
+ const c = createCipheriv("chacha20", key, iv);
106
+ return Buffer.concat([c.update(Buffer.alloc(len)), c.final()]);
107
+ }
108
+ export function permSeed(kPerm, nonce) {
109
+ return Buffer.from(hkdfSync("sha256", kPerm, nonce, INFO_PERM_SEED, KEY_LEN));
110
+ }
111
+ export function buildPermutation(seed, n) {
112
+ const perm = Array.from({ length: n }, (_, i) => i);
113
+ if (n <= 1)
114
+ return perm;
115
+ const ks = keystream(seed, n * 4);
116
+ for (let i = n - 1; i > 0; i--) {
117
+ const j = ks.readUInt32LE(i * 4) % (i + 1);
118
+ [perm[i], perm[j]] = [perm[j], perm[i]];
119
+ }
120
+ return perm;
121
+ }
122
+ function permute(buf, seed) {
123
+ const perm = buildPermutation(seed, buf.length);
124
+ const out = Buffer.alloc(buf.length);
125
+ for (let k = 0; k < buf.length; k++)
126
+ out[k] = buf[perm[k]];
127
+ return out;
128
+ }
129
+ // ── 메인: HMSOFT 복합 암호화 ───────────────────────────────────────
130
+ /** 단일 키(Buffer) 또는 키링(Keyring)으로 암호화. 키링이면 primary 키를 사용. */
131
+ export function hmsoftEncrypt(plaintext, keyOrRing) {
132
+ let key;
133
+ let keyId;
134
+ if (Buffer.isBuffer(keyOrRing)) {
135
+ key = keyOrRing;
136
+ keyId = "0";
137
+ }
138
+ else {
139
+ keyId = keyOrRing.primaryId;
140
+ key = keyOrRing.keys[keyId];
141
+ if (!key)
142
+ throw new Error(`키링에 primaryId '${keyId}' 키가 없습니다.`);
143
+ }
144
+ if (key.length !== KEY_LEN)
145
+ throw new Error("키는 32바이트여야 합니다. loadKey()/loadKeyring()을 사용하세요.");
146
+ if (!KEY_ID_RE.test(keyId))
147
+ throw new Error(`잘못된 keyId '${keyId}' (영숫자, _ , - 만 허용)`);
148
+ const { kAes, kChacha, kPerm } = deriveKeys(key);
149
+ // ① AES-256-GCM
150
+ const aesIv = randomBytes(AES_IV_LEN);
151
+ const ac = createCipheriv(ALGO_AES, kAes, aesIv);
152
+ const aesCt = Buffer.concat([ac.update(plaintext, "utf8"), ac.final()]);
153
+ const blob0 = Buffer.concat([aesIv, ac.getAuthTag(), aesCt]);
154
+ // ② ChaCha20-Poly1305
155
+ const cNonce = randomBytes(CHACHA_NONCE_LEN);
156
+ const cc = createCipheriv(ALGO_CHACHA, kChacha, cNonce, { authTagLength: TAG_LEN });
157
+ const chaCt = Buffer.concat([cc.update(blob0), cc.final()]);
158
+ const blob1 = Buffer.concat([chaCt, cc.getAuthTag()]);
159
+ // ③ HMSOFT 셔플
160
+ const seed = permSeed(kPerm, cNonce);
161
+ const blob2 = permute(blob1, seed);
162
+ const payload = Buffer.concat([cNonce, blob2]);
163
+ return `${TOKEN_PREFIX}:${TOKEN_VERSION}:${keyId}:${payload.toString("base64url")}`;
164
+ }
165
+ // ── 비밀번호 해싱 (단방향, 복호화 불가) ─────────────────────────────
166
+ const SCRYPT_N = 1 << 15;
167
+ const SCRYPT_r = 8;
168
+ const SCRYPT_p = 1;
169
+ const SCRYPT_KEYLEN = 32;
170
+ const SCRYPT_MAXMEM = 128 * SCRYPT_N * SCRYPT_r * 2;
171
+ export function hashPassword(password) {
172
+ const salt = randomBytes(16);
173
+ const hash = scryptSync(password, salt, SCRYPT_KEYLEN, {
174
+ N: SCRYPT_N,
175
+ r: SCRYPT_r,
176
+ p: SCRYPT_p,
177
+ maxmem: SCRYPT_MAXMEM,
178
+ });
179
+ return [
180
+ "scrypt",
181
+ SCRYPT_N,
182
+ SCRYPT_r,
183
+ SCRYPT_p,
184
+ salt.toString("base64url"),
185
+ Buffer.from(hash).toString("base64url"),
186
+ ].join(":");
187
+ }
package/dist/demo.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/demo.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 데모: HMSOFT 복합 암호화 + 비밀번호 해싱
3
+ * 실행: npm run demo
4
+ */
5
+ import { generateKey, loadKey, hmsoftEncrypt, hashPassword } from "./index.js";
6
+ if (!process.env.HMSOFT_ENC_KEY) {
7
+ process.env.HMSOFT_ENC_KEY = generateKey();
8
+ console.log("[demo] 임시 마스터 키 생성됨 (실제로는 환경변수에 고정 보관)\n");
9
+ }
10
+ const key = loadKey();
11
+ const secret = "홍길동 / 901010-1234567";
12
+ const t1 = hmsoftEncrypt(secret, key);
13
+ const t2 = hmsoftEncrypt(secret, key);
14
+ console.log("원본 :", secret);
15
+ console.log("토큰 #1 :", t1);
16
+ console.log("토큰 #2 :", t2);
17
+ console.log("→ 같은 평문도 매번 다른 토큰:", t1 !== t2);
18
+ console.log("→ HMSOFT 고유 prefix:", t1.startsWith("HMSOFT:v1:"));
19
+ console.log("\n비밀번호 해시:", hashPassword("my-password-123"));
20
+ console.log("(복호화 불가 — 검증은 @hmsoft/dec의 verifyPassword)");
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @hmsoft/enc — 쓰기(저장) 쪽 SDK
3
+ *
4
+ * // 단일 키
5
+ * import { hmsoftEncrypt, hashPassword, loadKey } from "@hmsoft/enc";
6
+ * const key = loadKey();
7
+ * const enc = hmsoftEncrypt("주민번호 등 민감정보", key);
8
+ *
9
+ * // 키 회전(키링) — primary 키로 신규 암호화
10
+ * import { hmsoftEncrypt, loadKeyring } from "@hmsoft/enc";
11
+ * const ring = loadKeyring();
12
+ * const enc = hmsoftEncrypt("민감정보", ring);
13
+ */
14
+ export { hmsoftEncrypt, hashPassword, loadKey, loadKeyring, generateKey, KEY_LEN, } from "./crypto.js";
15
+ export type { Keyring } from "./crypto.js";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @hmsoft/enc — 쓰기(저장) 쪽 SDK
3
+ *
4
+ * // 단일 키
5
+ * import { hmsoftEncrypt, hashPassword, loadKey } from "@hmsoft/enc";
6
+ * const key = loadKey();
7
+ * const enc = hmsoftEncrypt("주민번호 등 민감정보", key);
8
+ *
9
+ * // 키 회전(키링) — primary 키로 신규 암호화
10
+ * import { hmsoftEncrypt, loadKeyring } from "@hmsoft/enc";
11
+ * const ring = loadKeyring();
12
+ * const enc = hmsoftEncrypt("민감정보", ring);
13
+ */
14
+ export { hmsoftEncrypt, hashPassword, loadKey, loadKeyring, generateKey, KEY_LEN, } from "./crypto.js";
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@hm-soft/enc",
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
+ "encryption",
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
+ }