【发布时间】:2021-06-08 15:05:24
【问题描述】:
使用 iText7,我正在尝试签署 PDF 以获取外部实体的签名。
该过程必须按如下方式实现
- 使用 Web 服务并获取证书,
- 获取要签名的 PDF 哈希。在发送到外部实体进行签名之前,哈希必须有前缀。
- 为此我创建了一个临时 PDF。
- 在信息交换中使用 Web 服务。
- 发送哈希;
- 通过短信获得确认;
- 获取签名哈希。
- 我使用已签名的哈希对最终 PDF 进行签名。
问题,我收到the document has been altered or corrupted after applying the signature 的错误。
项目实施是。
private final String _pdfToBeSigned = "C:/tmp/ama/PDF1.pdf";
private final String _temporaryPdf = "C:/tmp/ama/PDF1_empty.pdf";
private final String _finalPdf = "C:/tmp/ama/PDF1_assinado.pdf";
private final String _signatureFieldname = "sign1";
private static X509Certificate[] _chain = null;
private static Collection<byte[]> _crlBytesList = null;
private static Collection<byte[]> _ocspBytesList = null;
public static void main(String[] a) throws GeneralSecurityException, IOException {
//Certificates (3) of the service are obtained.
_chain = getCertificates();
TSAClientBouncyCastle tsaClient = new TSAClientBouncyCastle("https://freetsa.org/tsr");
CrlClientOnline crlClients = new CrlClientOnline(_chain);
OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle(null);
_crlBytesList = getCrlByteList(crlClients);
_ocspBytesList = getOcspBytesList(ocspClient);
TestSign test = new TesteSign();
List<byte[]> hashs = test.getPreSignPDF(tsaClient, ocspClient);
//Note: send hash to sign and wait for return of SMS with code
// if SMS code ok, the signed hash is obtained.
byte[] hashSignedForAma = getHashSignedByAma(hashs.get(0));
//Finally sign the PDF
test.setFinalSignPDF(hashSignedForAma, hashs.get(1), tsaClient);
}
private static Collection<byte[]> getCrlByteList(CrlClientOnline crlClients){
if(crlClients == null) return null;
Collection<byte[]> coll = null;
for(int i=0;i<_chain.length;i++) {
Collection<byte[]> tmp = crlClients.getEncoded(_chain[i], null);
if(null != tmp ) {
coll = new ArrayList<byte[]>();
coll.addAll(tmp);
}
}
return coll;
}
private static Collection<byte[]> getOcspBytesList(OcspClientBouncyCastle ocspClient) {
if(_chain.length <= 1 ||
ocspClient == null) {
return null;
}
Collection<byte[]> list = new ArrayList<byte[]>();
for(var i = 0; i < _chain.length - 1; i++) {
byte[] encoded = ocspClient.getEncoded(_chain[i], _chain[i + 1], null);
if(encoded != null) {
list.add(encoded);
}
}
return list;
}
获取要签名的 PDF 哈希。在发送给外部实体进行签名之前,哈希必须有一个前缀,并为此创建一个临时 PDF。
public List<byte[]> getPreSignPDF(TSAClientBouncyCastle tsaClient_, OcspClientBouncyCastle ocspClient_) throws GeneralSecurityException, IOException {
try (OutputStream ops = new FileOutputStream(_temporaryPdf);){
PdfReader reader = new PdfReader(_pdfToBeSigned);
StampingProperties prop = new StampingProperties();
PdfSigner pdfSigner = new PdfSigner(reader, ops, prop);
pdfSigner.setFieldName(_signatureFieldname);
PdfSignatureAppearance appearance = pdfSigner.getSignatureAppearance();
appearance.setPageRect(new Rectangle(10,750,150,50))
.setPageNumber(1)
.setLayer2FontSize(6f)
.setReason("reason")
.setLocation("location")
.setCertificate(_chain[0]);
Prepare4AmaSigningContainer container = new Prepare4AmaSigningContainer();
//calculate estimed size
int estimatedSize = 8192 + //initial base container size
( ocspClient_ != null ? 4192 : 0 ) +
( tsaClient_ != null ? 4600 : 0 );
if(_crlBytesList != null) {
for (byte[] bs : _crlBytesList) {
estimatedSize+= bs.length + 10;
}
}
pdfSigner.signExternalContainer(container, estimatedSize);
byte[] HashForSigning = container.getHashToBeSignedByAma();
byte[] NakeHash = container.getHashToBeSignedByAma();
List<byte[]> array = new ArrayList<byte[]>();
array.add(HashForSigning); //idx 0
array.add(NakeHash); //idx 1
return array;
}
}
//***** CLASS ****
class Prepare4AmaSigningContainer extends ExternalBlankSignatureContainer{
private final byte[] _sha256SigPrefix = {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte)0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20};
private byte[] hashToBeSignedByAma;
private byte[] nakeHash = null;
public Prepare4AmaSigningContainer(){
super(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached);
}
public byte[] getHashToBeSignedByAma() {
return hashToBeSignedByAma;
}
public byte[] getNakeHash() {
return nakeHash;
}
@Override
public byte[] sign(InputStream data){
try {
// create pdf pkcs7 for signing the document
BouncyCastleDigest digest = new BouncyCastleDigest();
PdfPKCS7 sgn = new PdfPKCS7(null, _chain, DigestAlgorithms.SHA256, null, digest, false);
// get hash for document bytes
nakeHash = DigestAlgorithms.digest(data, digest.getMessageDigest(DigestAlgorithms.SHA256));
// get attributes
byte[] docBytes = sgn.getAuthenticatedAttributeBytes(nakeHash, PdfSigner.CryptoStandard.CMS, _crlBytesList, _crlBytesList);
// hash it again
try(InputStream myInputStream = new ByteArrayInputStream(docBytes);){
byte[] docBytesHash = DigestAlgorithms.digest(myInputStream, digest.getMessageDigest("SHA256"));
//prepend sha256 prefix to hash for send signed
hashToBeSignedByAma = new byte[_sha256SigPrefix.length + docBytesHash.length];
System.arraycopy(_sha256SigPrefix, 0, hashToBeSignedByAma, 0, _sha256SigPrefix.length );
System.arraycopy(docBytesHash, 0, hashToBeSignedByAma, _sha256SigPrefix.length, docBytesHash.length );
return new byte[0]; // empty array
}
}catch (IOException | GeneralSecurityException ioe) {
throw new RuntimeException(ioe);
}
}
}
使用签名的哈希我签署临时 PDF
public void setFinalSignPDF(byte[] HashSignedForAma_, byte[] nakedHashFromIntermediaryPdf_, TSAClientBouncyCastle tsaClient_) throws IOException, GeneralSecurityException{
try (OutputStream writer = new FileOutputStream(_finalPdf);) {
PdfReader pdfReader = new PdfReader(_temporaryPdf);
PdfDocument document = new PdfDocument(pdfReader);
InjectAmaSignatureContainer finalContainer = new InjectAmaSignatureContainer(
HashSignedForAma_,
nakedHashFromIntermediaryPdf_,
tsaClient_);
PdfSigner.signDeferred(document, _signatureFieldname, writer, finalContainer);
}
}
//***** CLASS ****
class InjectAmaSignatureContainer implements IExternalSignatureContainer {
private byte[] documentHash;
private byte[] signature;
private TSAClientBouncyCastle tsaClient;
private byte[] dados = null;
public InjectAmaSignatureContainer(byte[] signature_, byte[] documentHash_, TSAClientBouncyCastle tsaClient_) {
signature = signature_;
documentHash = documentHash_;
tsaClient = tsaClient_;
}
public byte[] getDados() {
return dados;
}
@Override
public byte[] sign(InputStream is) throws GeneralSecurityException {
BouncyCastleDigest digest = new BouncyCastleDigest();
PdfPKCS7 sgn = new PdfPKCS7(null,
_chain,
DigestAlgorithms.SHA256,
null,
digest,
false);
sgn.setExternalDigest(signature, null, "RSA");
byte[] encodedSig = sgn.getEncodedPKCS7(documentHash, PdfSigner.CryptoStandard.CMS, tsaClient, _ocspBytesList, _crlBytesList);
return encodedSig;
}
@Override
public void modifySigningDictionary(PdfDictionary signDic) {
}
}
谢谢
编辑:
方法中的错误修复:Prepare4AmaSigningContainer
byte[] docBytes = sgn.getAuthenticatedAttributeBytes(nakeHash, PdfSigner.CryptoStandard.CMS, _ocspBytesList, _crlBytesList);
【问题讨论】:
-
请分享一个由您的代码签名的示例 pdf 以供分析。
-
嗨,谢谢。 link 用于 PDF 签名。
-
好的,
Prepare4AmaSigningContainer中有一个错误,您的sgn.getAuthenticatedAttributeBytes调用将_crlBytesList用于两个参数;我认为其中之一应该是_ocspBytesList。但我认为还有其他问题。 -
是的,我的错是对的。我已经修复了它,但它仍然有同样的问题。我尝试了几种方法(您建议了一些方法),但它们从未给我正确的签名。如果有更好的解决问题的方法...我会实施的,谢谢
-
“如果有更好的方法来解决这个问题......我会实施它,谢谢” - 也许。在
main中,您按顺序执行最后三个指令(test.getPreSignPDF、getHashSignedByAma、test.setFinalSignPDF)。如果这相当于您的最终设计,我们可以轻松地将其设为一步签名,并摆脱延迟签名的步骤。