TypeScript에서 PDF 문서를 보호하고 서명하는 방법
이 가이드는 TypeScript용 Aspose.PDF FOSS를 사용하여 PDF 문서를 암호화, 인증, 서명 및 검증하는 방법을 보여줍니다. Document.Save()와 Document.Open()은 수신자 인증서에 대한 공개키 암호화를 처리하고, Document.Certify(), Document.Sign(), Document.VerifySignatures()는 PAdES 스타일 디지털 서명을 처리합니다. Node.js 22 이상이 필요합니다.
단계별 가이드
1단계: 패키지 설치
git clone https://github.com/aspose-pdf-foss/Aspose.PDF-FOSS-for-TypeScript.git
cd Aspose.PDF-FOSS-for-TypeScript
npm install
npm run build패키지를 설치한 후, 새 TypeScript 파일에서 Document 클래스를 가져와 설치를 확인하십시오 — 패키지가 설치되면 이 구문이 오류 없이 해석되어야 합니다:
import { Document } from '@asposefoss/pdf';2단계: 필요한 클래스 가져오기
파일을 열고, 저장하고, 서명하고 검증하기 위해 Document을(를) 가져옵니다; 아래 서명 및 암호화 단계에서는 단순 옵션 객체를 전달하므로 추가 가져오기가 필요하지 않습니다:
import { Document } from '@asposefoss/pdf';단계 3: 수신자 인증서로 문서를 암호화
Document.Save()은(는) 하나 이상의 recipients를 포함하는 encrypt 옵션을 받아들이며, 각 recipients는 인증서(PEM 문자열 또는 DER 바이트), algorithm, 그리고 공유 permissions로 식별됩니다:
const doc = Document.OpenFile('report.pdf');
const bytes = doc.Save({
encrypt: {
recipients: [{ certificate: recipientCertPem }],
algorithm: 'aes256', // 'aes256' (default) | 'aes128' | 'rc4'
permissions: { copying: false }, // shared across all recipients
},
});단계 4: 암호화된 문서 열기
일치하는 개인 키와 인증서 또는 PKCS#12 번들을 사용하여 recipient 옵션을 Document.Open()에 전달합니다:
const opened = Document.Open(bytes, {
recipient: { privateKey, certificate: recipientCertPem },
// or: recipient: { pkcs12: p12Bytes, passphrase: '…' },
});
console.log(opened.Permissions); // recovered permission flags (not enforced)
단계 5: 문서 인증 및 서명
Document.Certify()와 Document.Sign()은 모두 비동기이며, 신원(certificate + privateKey)과 서명 필드, 외관, 이유를 설명하는 옵션을 받습니다. 인증은 전체 파일에 대해 먼저 수행되어야 하며, 이후 추가 승인 서명이 순차적으로 추가됩니다:
async function certifyAndSign(sourcePath: string, signaturePageIndex: number): Promise<void> {
const certifying = Document.OpenFile(sourcePath);
await certifying.Certify(
{ certificate: authorCert, privateKey: authorKey },
{
permissions: 'form-fill',
reason: 'Certifying the document',
fieldName: 'Certification',
appearance: { page: signaturePageIndex, rect: [400, 100, 550, 140] },
},
);
const certifiedBytes = certifying.Save();
const approving = Document.Open(certifiedBytes);
await approving.Sign(
{ certificate: approverCert, privateKey: approverKey },
{ reason: 'Approved for publication', fieldName: 'Approval', subFilter: 'PAdES' },
);
approving.WriteTo('signed.pdf');
}단계 6: 서명 검증
Document.VerifySignatures()은 비동기이며 서명 필드당 하나의 SignatureReport을 반환하고, 각각 암호학적 integrity, signature 유효성 및 coversWholeFile 여부를 보고합니다:
async function verify(path: string): Promise<void> {
const doc = Document.OpenFile(path);
const reports = await doc.VerifySignatures();
for (const r of reports) {
console.log(`${r.name}: integrity=${r.integrity} signature=${r.signature} `
+ `coversWholeFile=${r.coversWholeFile} docMDP=${r.docMDP}`);
}
}일반적인 문제 및 해결 방법
Document.Sign() / Document.Certify() throw 또는 hang. 두 경우 모두 비동기입니다 — await 그 호출. 잊어버리기 await 반환된 프로미스가 해결되지 않은 상태로 남고, 쓰기가 서명이 완료되기 전에 발생합니다.
이후의 승인 서명이 인증을 무효화합니다. 점진적으로 서명하십시오: 인증된 바이트를 먼저 저장합니다 (certifying.Save()), 이를 사용해 다시 엽니다 Document.Open(), 그런 다음 호출합니다 Sign() 그 다시 연 문서에서 — 전체 재작성으로 증분 추가 대신 쓰면 인증서의 /ByteRange 다이제스트.
VerifySignatures() reports coversWholeFile: false 첫 번째 서명에 대해서는 하지만 true 마지막에 대해서는. 이는 인증 후 서명 체인에서 예상되는 동작입니다: 인증서는 승인이 추가되기 전에 서명되었으므로, 가장 최근 서명의 /ByteRange 파일 끝까지 확장됩니다.
올바른 개인 키를 사용해도 복호화가 실패합니다. 확인하십시오 certificate 전달된 recipient 문서가 암호화된 정확한 인증서와 일치합니다 Document.Save()’s recipients 목록 — 새 키 쌍으로 재발급된 인증서는 이전 인증서로 암호화된 데이터를 복호화할 수 없습니다.
자주 묻는 질문
문서를 하나 이상의 수신자에게 암호화할 수 있나요?
예 — recipients은(는) Document.Save()의 encrypt 옵션에서 배열을 허용합니다; 해당 수신자의 일치하는 개인 키로 결과 파일을 열 수 있습니다.
Document.Sign()이(가) 생성하는 서명 형식은 무엇인가요?
sign 옵션에 subFilter: 'PAdES'을(를) 전달하면 PAdES 호환 서명이 생성됩니다; 이를 생략하면 라이브러리의 기본 서명 서브필터를 사용합니다.
문서가 인증된 것인지 단순히 서명된 것인지 어떻게 확인하나요?
Document.VerifySignatures()가 반환한 SignatureReport의 docMDP 필드를 검사하십시오 — 인증 서명은 DocMDP 권한 판정을 보고하고, 승인 전용 서명은 그렇지 않습니다.
복구된 Permissions이(가) Document.Open() 후에 라이브러리에 의해 강제 적용됩니까?
아니요 — opened.Permissions은(는) 검사용으로 암호화된 파일에 기록된 권한 플래그를 보고합니다; 애플리케이션에서 이를 강제 적용하는 것은 호출자의 책임입니다.