-
Notifications
You must be signed in to change notification settings - Fork 0
/
pki.js
53 lines (42 loc) · 1.83 KB
/
pki.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Copyright © 2024 FirstTimeEZ
* https://github.com/FirstTimeEZ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TAGS } from 'simple-asn1';
import * as asn from 'simple-asn1';
export function extractECPoint(derKey) {
let offset = 0;
if (derKey[offset++] !== TAGS.SEQUENCE) throw new Error('Expected sequence');
offset += asn.skipDERLength(derKey.slice(offset));
if (derKey[offset++] !== TAGS.SEQUENCE) throw new Error('Expected algorithm sequence');
const algLength = asn.readDERLength(derKey.slice(offset));
offset += asn.skipDERLength(derKey.slice(offset)) + algLength;
if (derKey[offset++] !== 0x03) throw new Error('Expected bit string');
const bitStringLength = asn.readDERLength(derKey.slice(offset));
offset += asn.skipDERLength(derKey.slice(offset));
offset++;
const remainingLength = bitStringLength - 1;
if (remainingLength !== derKey.length - offset) {
throw new Error('Invalid bit string length for EC point');
}
if (derKey[offset] !== TAGS.OCTET_STRING) {
throw new Error('Expected uncompressed EC point (TAGS.OCTET_STRING)');
}
const point = derKey.slice(offset + 1, offset + remainingLength);
if (point.length !== 64) {
throw new Error(`Invalid EC point length: ${point.length} (expected 64 bytes)`);
}
return point;
}