Статус: Новичок
Группы: Участники
Зарегистрирован: 24.05.2019(UTC) Сообщений: 8 Откуда: Москва Сказал(а) «Спасибо»: 1 раз
|
Добрый день до этого использовали jcp 1.0.54, ГОСТ 2001 сейчас пытаемся использовать jcp-2.0.40132-A, ГОСТ 2012 открытый ключ https://onebox.huawei.co...db789408d50c51d47cdb864dфайлы электронной подписи https://onebox.huawei.co...6d759178c3e992f2ba4f9aa1Примеры кода для подписей: CertificateHelper (DiadocSDK 2.13.0)
Код:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package Diadoc.Api;
import com.objsys.asn1j.runtime.Asn1BerDecodeBuffer;
import com.objsys.asn1j.runtime.Asn1BerEncodeBuffer;
import com.objsys.asn1j.runtime.Asn1Null;
import com.objsys.asn1j.runtime.Asn1ObjectIdentifier;
import com.objsys.asn1j.runtime.Asn1OctetString;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.commons.codec.binary.Hex;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.CMSVersion;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.CertificateChoices;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.CertificateSet;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.ContentInfo;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.DigestAlgorithmIdentifier;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.DigestAlgorithmIdentifiers;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.EncapsulatedContentInfo;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.IssuerAndSerialNumber;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.SignatureAlgorithmIdentifier;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.SignatureValue;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.SignedData;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.SignerIdentifier;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.SignerInfo;
import ru.CryptoPro.JCP.ASN.CryptographicMessageSyntax.SignerInfos;
import ru.CryptoPro.JCP.ASN.PKIX1Explicit88.CertificateSerialNumber;
import ru.CryptoPro.JCP.ASN.PKIX1Explicit88.Name;
import ru.CryptoPro.JCP.params.OID;
public class CertificateHelper {
private static final String STR_CMS_OID_DATA = "1.2.840.113549.1.7.1";
private static final String STR_CMS_OID_SIGNED = "1.2.840.113549.1.7.2";
public CertificateHelper() {
}
public static byte[] createCMS(byte[] buffer, byte[] sign, Certificate cert, boolean detached) throws Exception {
ContentInfo all = new ContentInfo();
all.contentType = new Asn1ObjectIdentifier((new OID("1.2.840.113549.1.7.2")).value);
SignedData cms = new SignedData();
all.content = cms;
cms.version = new CMSVersion(1L);
cms.digestAlgorithms = new DigestAlgorithmIdentifiers(1);
DigestAlgorithmIdentifier a = new DigestAlgorithmIdentifier((new OID("1.2.643.2.2.9")).value);
a.parameters = new Asn1Null();
cms.digestAlgorithms.elements[0] = a;
if (detached) {
cms.encapContentInfo = new EncapsulatedContentInfo(new Asn1ObjectIdentifier((new OID("1.2.840.113549.1.7.1")).value), (Asn1OctetString)null);
} else {
cms.encapContentInfo = new EncapsulatedContentInfo(new Asn1ObjectIdentifier((new OID("1.2.840.113549.1.7.1")).value), new Asn1OctetString(buffer));
}
cms.certificates = new CertificateSet(1);
ru.CryptoPro.JCP.ASN.PKIX1Explicit88.Certificate certificate = new ru.CryptoPro.JCP.ASN.PKIX1Explicit88.Certificate();
Asn1BerDecodeBuffer decodeBuffer = new Asn1BerDecodeBuffer(cert.getEncoded());
certificate.decode(decodeBuffer);
cms.certificates.elements = new CertificateChoices[1];
cms.certificates.elements[0] = new CertificateChoices();
cms.certificates.elements[0].set_certificate(certificate);
cms.signerInfos = new SignerInfos(1);
cms.signerInfos.elements[0] = new SignerInfo();
cms.signerInfos.elements[0].version = new CMSVersion(1L);
cms.signerInfos.elements[0].sid = new SignerIdentifier();
byte[] encodedName = ((X509Certificate)cert).getIssuerX500Principal().getEncoded();
Asn1BerDecodeBuffer nameBuf = new Asn1BerDecodeBuffer(encodedName);
Name name = new Name();
name.decode(nameBuf);
CertificateSerialNumber num = new CertificateSerialNumber(((X509Certificate)cert).getSerialNumber());
cms.signerInfos.elements[0].sid.set_issuerAndSerialNumber(new IssuerAndSerialNumber(name, num));
cms.signerInfos.elements[0].digestAlgorithm = new DigestAlgorithmIdentifier((new OID("1.2.643.2.2.9")).value);
cms.signerInfos.elements[0].digestAlgorithm.parameters = new Asn1Null();
cms.signerInfos.elements[0].signatureAlgorithm = new SignatureAlgorithmIdentifier((new OID("1.2.643.2.2.19")).value);
cms.signerInfos.elements[0].signatureAlgorithm.parameters = new Asn1Null();
cms.signerInfos.elements[0].signature = new SignatureValue(sign);
Asn1BerEncodeBuffer asnBuf = new Asn1BerEncodeBuffer();
all.encode(asnBuf, true);
return asnBuf.getMsgCopy();
}
public static byte[] CMSSign(byte[] data, PrivateKey key, Certificate cert, boolean detached) throws Exception {
Signature signature = Signature.getInstance("GOST3411withGOST3410EL");
signature.initSign(key);
signature.update(data);
byte[] sign = signature.sign();
return createCMS(data, sign, cert, detached);
}
public static byte[] sign(X509Certificate cert, byte[] data) throws Exception {
PrivateKey privateKey = getPrivateKey(cert, (char[])null);
return CMSSign(data, privateKey, cert, false);
}
public static PrivateKey getPrivateKey(X509Certificate cert, char[] password) {
try {
KeyStore keystore = KeyStore.getInstance("HDImageStore");
keystore.load((InputStream)null, (char[])null);
Enumeration en = keystore.aliases();
while(en.hasMoreElements()) {
String s = (String)en.nextElement();
if (keystore.isKeyEntry(s)) {
Certificate[] kcerts = keystore.getCertificateChain(s);
if (kcerts[0] instanceof X509Certificate) {
X509Certificate x509 = (X509Certificate)kcerts[0];
if (getThumbPrint(x509).startsWith(getThumbPrint(cert))) {
return (PrivateKey)keystore.getKey(s, password);
}
}
}
if (keystore.isCertificateEntry(s)) {
Certificate c = keystore.getCertificate(s);
if (c instanceof X509Certificate && getThumbPrint((X509Certificate)c).startsWith(getThumbPrint(cert))) {
return (PrivateKey)keystore.getKey(s, password);
}
}
}
} catch (Exception var7) {
var7.printStackTrace();
}
return null;
}
public static String CertificateToString(X509Certificate certificate) {
String subject = certificate.getSubjectDN().getName();
int cnStartIndex = subject.indexOf("CN=");
if (cnStartIndex == -1) {
return subject;
} else {
String commonName = subject.substring(cnStartIndex + 3);
int commaIndex = commonName.indexOf(44);
if (commaIndex == -1) {
commaIndex = commonName.indexOf(59);
}
return commaIndex == -1 ? commonName : commonName.substring(0, commaIndex);
}
}
public static String getThumbPrint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
return new String(Hex.encodeHex(digest));
}
public static List<X509Certificate> GetCertificatesFromPersonalStore() {
ArrayList certs = new ArrayList();
try {
KeyStore keystore = KeyStore.getInstance("HDImageStore");
keystore.load((InputStream)null, (char[])null);
Enumeration en = keystore.aliases();
while(en.hasMoreElements()) {
String s = (String)en.nextElement();
if (keystore.isKeyEntry(s)) {
Certificate[] kcerts = keystore.getCertificateChain(s);
if (kcerts[0] instanceof X509Certificate) {
X509Certificate x509 = (X509Certificate)kcerts[0];
certs.add(x509);
}
}
if (keystore.isCertificateEntry(s)) {
Certificate c = keystore.getCertificate(s);
if (c instanceof X509Certificate) {
certs.add((X509Certificate)c);
}
}
}
return certs;
} catch (Exception var6) {
var6.printStackTrace();
return null;
}
}
public static X509Certificate GetCertificateFromBytes(byte[] bytes) throws CertificateException {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
return (X509Certificate)certFactory.generateCertificate(new ByteArrayInputStream(bytes));
}
}
DiadocSenderAdapter (наше интеграционное решение)
Код:
package com.luxoft.huawei.docflow.diadoc.adapter;
import Diadoc.Api.CertificateHelper;
import Diadoc.Api.GeneratedFile;
import Diadoc.Api.Proto.DocumentIdProtos.DocumentId;
import Diadoc.Api.Proto.Events.DiadocMessage_GetApiProtos;
import Diadoc.Api.Proto.Events.DiadocMessage_GetApiProtos.AttachmentType;
import Diadoc.Api.Proto.Events.DiadocMessage_PostApiProtos;
import Diadoc.Api.Proto.Events.DiadocMessage_PostApiProtos.*;
import Diadoc.Api.Proto.Invoicing.AcceptanceCertificateInfoProtos.AcceptanceCertificateSellerTitleInfo;
import Diadoc.Api.Proto.Invoicing.SignerProtos;
import Diadoc.Api.Proto.Invoicing.Torg12InfoProtos.Torg12SellerTitleInfo;
import Diadoc.Api.Proto.Invoicing.UniversalTransferDocumentInfoProtos;
import com.google.protobuf.ByteString;
import com.luxoft.huawei.docflow.config.DiadocConfig;
import com.luxoft.huawei.docflow.config.SecurityConfig;
import com.luxoft.huawei.docflow.db.entity.*;
import com.luxoft.huawei.docflow.db.repository.MetaDataRepository;
import com.luxoft.huawei.docflow.diadoc.DiadocAdapter;
import com.luxoft.huawei.docflow.diadoc.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class DiadocSenderAdapter extends DiadocAdapter {
@Autowired
public DiadocSenderAdapter(DiadocConfig config, SecurityConfig securityConfig) throws Exception {
super(config, securityConfig);
}
@Autowired
private MetaDataRepository metaDataRepository;
/**
* Отправка неформализованного документа
*
* @param senderBoxId бокс отправителя
* @param receiverBoxId бокс получателя
* @param document документ
* @return структура, содержащая идентификатор сообщения и документа в системе диадок
* @throws Exception исключение при взаимодействии с диадок
*/
public Message sendNonFormalDocument(String senderBoxId, String receiverBoxId, Document document) throws Exception {
boolean signed = document.getDocumentStatus().equals("OutboundWaitingForRecipientSignature");
MessageToPost.Builder messageBuilder = createMessageToPostNonFormalized(senderBoxId, receiverBoxId, document, signed);
//MessageToPost.Builder messageBuilder = createMessageToPostNonFormalized(senderBoxId, receiverBoxId, document, true);
return sendDocument(messageBuilder);
}
private Message sendDocument(MessageToPost.Builder messageBuilder) throws IOException {
MessageToPost messageToPost = messageBuilder.build();
DiadocMessage_GetApiProtos.Message postedMessage = diadocApi.PostMessage(messageToPost);
return Message.generate(postedMessage);
}
private MessageToPost.Builder createMessageToPostNonFormalized(String senderBoxId, String receiverBoxId, Document document, boolean signed) throws Exception {
MessageToPost.Builder messageToPost = createMessageToPost(senderBoxId, receiverBoxId);
NonformalizedAttachment.Builder nonformalized = messageToPost.addNonformalizedDocumentsBuilder();
nonformalized.setFileName(document.getDocumentName());
nonformalized.setNeedRecipientSignature(signed);
if (document.getDocumentComment() != null) {
nonformalized.setComment(document.getDocumentComment());
}
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
nonformalized.addAllInitialDocumentIds(initialDocumentIds);
}
ByteString content = ByteString.copyFrom(document.getDocumentContent().getDocumentContent());
ByteString signature = ByteString.copyFrom(CertificateHelper.sign(certificate, content.toByteArray()));
SignedContent.Builder signedContent = nonformalized.getSignedContentBuilder();
signedContent.setContent(content);
signedContent.setSignature(signature);
messageToPost.setToDepartmentId(document.getReciever().getDepId() != null ? document.getReciever().getDepId(): "");
messageToPost.setFromDepartmentId(document.getSender().getDepId() != null ? document.getSender().getDepId() : "");
return messageToPost;
}
private List<DocumentId> getInitialDiadocDocumentIds(Document document) {
List<DocumentId> initialDocumentIds = new ArrayList<>();
for (int i = 0; i < document.getInitialDocumentIds().size(); i++) {
Document initialDocument = document.getInitialDocumentIds().get(i);
DocumentId.Builder documentIdBuilder = DocumentId.newBuilder();
documentIdBuilder.setMessageId(initialDocument.getMessageId());
documentIdBuilder.setEntityId(initialDocument.getDocumentId());
initialDocumentIds.add(documentIdBuilder.build());
}
return initialDocumentIds;
}
private MessageToPost.Builder createMessageToPost(String senderBoxId, String recieverBoxId) {
MessageToPost.Builder result = MessageToPost.newBuilder();
result.setFromBoxId(senderBoxId);
result.setToBoxId(recieverBoxId);
return result;
}
/**
* Отправка формализованного документа
* Важно!!! Отправляются документы следующих типов: Invoice, Torg12, XmlTorg12, AcceptanceCertificate, XmlAcceptanceCertificate
*
* @param senderBoxId бокс отправителя
* @param receiverBoxId бокс получателя
* @param document документ
* @return структура, содержащая идентификатор сообщения и документа в системе диадок
* @throws Exception исключение при взаимодействии с диадок или в случае передачи документа неподдерживаемого типа.
*/
public Message sendFormalDocument(String senderBoxId, String receiverBoxId, Document document) throws Exception {
MessageToPost.Builder messageBuilder;
AttachmentType attachmentType = AttachmentType.valueOf(document.getDocumentType().getId());
switch (attachmentType) {
case Invoice:
messageBuilder = generateInvoice(senderBoxId, receiverBoxId, document);
break;
case Torg12:
case XmlTorg12:
messageBuilder = generateTorg12(senderBoxId, receiverBoxId, document);
break;
case AcceptanceCertificate:
case XmlAcceptanceCertificate:
messageBuilder = generateAcceptanceTitle(senderBoxId, receiverBoxId, document);
break;
case Contract:
messageBuilder = generateContract(senderBoxId, receiverBoxId, document);
break;
case SupplementaryAgreement:
messageBuilder = generateSupplementaryAgreement(senderBoxId, receiverBoxId, document);
break;
case ProformaInvoice:
messageBuilder = generateProformaInvoice(senderBoxId, receiverBoxId, document);
break;
case UniversalTransferDocument:
messageBuilder = generateUniversalTransferDocument(senderBoxId,receiverBoxId,document);
break;
default:
throw new IllegalStateException("Param docType : " + attachmentType + " must be valid");
}
messageBuilder.setToDepartmentId(document.getReciever().getDepId() != null ? document.getReciever().getDepId(): "");
messageBuilder.setFromDepartmentId(document.getSender().getDepId() != null ? document.getSender().getDepId() : "");
return sendDocument(messageBuilder);
}
private MessageToPost.Builder generateAcceptanceTitle(String senderBoxId, String recieverBoxId, Document document) throws Exception {
byte[] documentContent = document.getDocumentContent().getDocumentContent();
AcceptanceCertificateSellerTitleInfo sellerTitleInfo = diadocApi.ParseAcceptanceCertificateSellerTitleXml(documentContent);
GeneratedFile sellerTitle = diadocApi.GenerateAcceptanceCertificateXmlForSeller(sellerTitleInfo);
byte[] content = sellerTitle.getContent();
byte[] signature = CertificateHelper.sign(certificate, content);
MessageToPost.Builder messageToPostBuilder = createMessageToPost(senderBoxId, recieverBoxId);
XmlDocumentAttachment.Builder acceptanceCertAttachmentBuilder = messageToPostBuilder.addXmlAcceptanceCertificateSellerTitlesBuilder();
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
acceptanceCertAttachmentBuilder.addAllInitialDocumentIds(initialDocumentIds);
}
SignedContent.Builder signedContentBuilder = acceptanceCertAttachmentBuilder.getSignedContentBuilder();
signedContentBuilder.setContent(ByteString.copyFrom(content));
signedContentBuilder.setSignature(ByteString.copyFrom(signature));
return messageToPostBuilder;
}
private MessageToPost.Builder generateTorg12(String senderBoxId, String recieverBoxId, Document document) throws Exception {
byte[] documentContent = document.getDocumentContent().getDocumentContent();
Torg12SellerTitleInfo torg12SellerTitleInfo = diadocApi.ParseTorg12SellerTitleXml(documentContent);
GeneratedFile torg12SellerFile = diadocApi.GenerateTorg12XmlForSeller(torg12SellerTitleInfo, true);
byte[] torg12Content = torg12SellerFile.getContent();
byte[] signature = CertificateHelper.sign(certificate, torg12Content);
MessageToPost.Builder torg12MessageBuilder = createMessageToPost(senderBoxId, recieverBoxId);
XmlDocumentAttachment.Builder torg12AttachmentBuilder = torg12MessageBuilder.addXmlTorg12SellerTitlesBuilder();
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
torg12AttachmentBuilder.addAllInitialDocumentIds(initialDocumentIds);
}
SignedContent.Builder signedContentBuilder = torg12AttachmentBuilder.getSignedContentBuilder();
signedContentBuilder.setContent(ByteString.copyFrom(torg12Content));
signedContentBuilder.setSignature(ByteString.copyFrom(signature));
return torg12MessageBuilder;
}
private MessageToPost.Builder generateInvoice(String senderBoxId, String recieverBoxId, Document document) throws Exception {
byte[] documentContent = document.getDocumentContent().getDocumentContent();
byte[] signature = CertificateHelper.sign(certificate, documentContent);
MessageToPost.Builder invoiceMessageBuilder = createMessageToPost(senderBoxId, recieverBoxId);
XmlDocumentAttachment.Builder invoiceAttachmentBuilder = invoiceMessageBuilder.addInvoicesBuilder();
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
invoiceAttachmentBuilder.addAllInitialDocumentIds(initialDocumentIds);
}
SignedContent.Builder signedContentBuilder = invoiceAttachmentBuilder.getSignedContentBuilder();
signedContentBuilder.setContent(ByteString.copyFrom(documentContent));
signedContentBuilder.setSignature(ByteString.copyFrom(signature));
return invoiceMessageBuilder;
}
private MessageToPost.Builder generateContract(String senderBoxId, String recieverBoxId, Document document) throws Exception {
byte[] documentContent = document.getDocumentContent().getDocumentContent();
byte[] signature = CertificateHelper.sign(certificate, documentContent);
MessageToPost.Builder contractMessageBuilder = createMessageToPost(senderBoxId, recieverBoxId);
ContractAttachment.Builder contractBuilder = contractMessageBuilder.addContractsBuilder();
contractBuilder.setDocumentDate(String.valueOf(document.getInsertTimestamp()));
List<MetaData> metaData = metaDataRepository.getMetaData(document.getDocumentContent().getId());
if (!metaData.isEmpty()){
ContractInfo contractInfo = (ContractInfo) metaData.get(0);
contractBuilder.setContractPrice(contractInfo.getContractPrice());
contractBuilder.setContractType(contractInfo.getContractType());
contractBuilder.setDocumentNumber(contractInfo.getDocumentNumber());
contractBuilder.setDocumentDate(contractInfo.getDocumentDate());
contractBuilder.setComment(document.getDocumentComment());
contractBuilder.setFileName(document.getDocumentName());
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
contractBuilder.addAllInitialDocumentIds(initialDocumentIds);
}
}
SignedContent.Builder signedContentBuilder = contractBuilder.getSignedContentBuilder();
signedContentBuilder.setContent(ByteString.copyFrom(documentContent));
signedContentBuilder.setSignature(ByteString.copyFrom(signature));
return contractMessageBuilder;
}
private MessageToPost.Builder generateSupplementaryAgreement(String senderBoxId, String recieverBoxId, Document document) throws Exception {
byte[] documentContent = document.getDocumentContent().getDocumentContent();
byte[] signature = CertificateHelper.sign(certificate, documentContent);
MessageToPost.Builder supplementaryAgreementMessageBuilder = createMessageToPost(senderBoxId, recieverBoxId);
SupplementaryAgreementAttachment.Builder supplementaryAgreementsBuilder = supplementaryAgreementMessageBuilder.addSupplementaryAgreementsBuilder();
supplementaryAgreementsBuilder.setDocumentDate(String.valueOf(document.getInsertTimestamp()));
List<MetaData> metaData = metaDataRepository.getMetaData(document.getDocumentContent().getId());
if (!metaData.isEmpty()) {
SupplementaryAgreementInfo supplementaryAgreementInfo = (SupplementaryAgreementInfo) metaData.get(0);
supplementaryAgreementsBuilder.setTotal(supplementaryAgreementInfo.getTotalPrice());
supplementaryAgreementsBuilder.setContractType(supplementaryAgreementInfo.getContractType());
supplementaryAgreementsBuilder.setContractNumber(supplementaryAgreementInfo.getContractNumber());
supplementaryAgreementsBuilder.setContractDate(supplementaryAgreementInfo.getContractDate());
supplementaryAgreementsBuilder.setContractType(supplementaryAgreementInfo.getContractType());
supplementaryAgreementsBuilder.setDocumentDate(supplementaryAgreementInfo.getDocumentDate());
supplementaryAgreementsBuilder.setDocumentNumber(supplementaryAgreementInfo.getDocumentNumber());
supplementaryAgreementsBuilder.setComment(document.getDocumentComment());
supplementaryAgreementsBuilder.setFileName(document.getDocumentName());
}
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
supplementaryAgreementsBuilder.addAllInitialDocumentIds(initialDocumentIds);
}
SignedContent.Builder signedContentBuilder = supplementaryAgreementsBuilder.getSignedContentBuilder();
signedContentBuilder.setContent(ByteString.copyFrom(documentContent));
signedContentBuilder.setSignature(ByteString.copyFrom(signature));
return supplementaryAgreementMessageBuilder;
}
private MessageToPost.Builder generateProformaInvoice(String senderBoxId, String recieverBoxId, Document document) throws Exception {
byte[] documentContent = document.getDocumentContent().getDocumentContent();
byte[] signature = CertificateHelper.sign(certificate, documentContent);
MessageToPost.Builder proformaInvoiceMessageBuilder = createMessageToPost(senderBoxId, recieverBoxId);
BasicDocumentAttachment.Builder proformaInvoicesBuilder = proformaInvoiceMessageBuilder.addProformaInvoicesBuilder();
proformaInvoicesBuilder.setDocumentDate(String.valueOf(document.getInsertTimestamp()));
List<MetaData> metaData = metaDataRepository.getMetaData(document.getDocumentContent().getId());
if (!metaData.isEmpty()) {
ProformaInvoiceInfo proformaInvoiceInfo = (ProformaInvoiceInfo) metaData.get(0);
proformaInvoicesBuilder.setDocumentDate(proformaInvoiceInfo.getDocumentDate());
proformaInvoicesBuilder.setDocumentNumber(proformaInvoiceInfo.getDocumentNumber());
proformaInvoicesBuilder.setTotal(proformaInvoiceInfo.getTotalPrice());
proformaInvoicesBuilder.setVat(proformaInvoiceInfo.getVat());
proformaInvoicesBuilder.setGrounds(proformaInvoiceInfo.getGrounds());
proformaInvoicesBuilder.setComment(document.getDocumentComment());
proformaInvoicesBuilder.setFileName(document.getDocumentName());
}
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
proformaInvoicesBuilder.addAllInitialDocumentIds(initialDocumentIds);
}
SignedContent.Builder signedContentBuilder = proformaInvoicesBuilder.getSignedContentBuilder();
signedContentBuilder.setContent(ByteString.copyFrom(documentContent));
signedContentBuilder.setSignature(ByteString.copyFrom(signature));
return proformaInvoiceMessageBuilder;
}
private MessageToPost.Builder generateUniversalTransferDocument(String senderBoxId, String recieverBoxId, Document document) throws Exception {
byte[] documentContent = document.getDocumentContent().getDocumentContent();
UniversalTransferDocumentInfoProtos.UniversalTransferDocumentSellerTitleInfo universalTransferDocumentSellerTitleInfo = diadocApi.ParseUniversalTransferDocumentSellerTitleXml(documentContent);
GeneratedFile universalTransferDocumentSellerFile = diadocApi.GenerateUniversalTransferDocumentXmlForSeller(universalTransferDocumentSellerTitleInfo, true);
byte[] universalTransferDocumentContent = universalTransferDocumentSellerFile.getContent();
byte[] signature = CertificateHelper.sign(certificate, universalTransferDocumentContent);
MessageToPost.Builder universalTransferDocumentMessageBuilder = createMessageToPost(senderBoxId, recieverBoxId);
XmlDocumentAttachment.Builder universalTransferDocumentAttachmentBuilder = universalTransferDocumentMessageBuilder.addUniversalTransferDocumentSellerTitlesBuilder();
if (document.getInitialDocumentIds() != null) {
//задаем init документы (для формирования пакета у получателя)
List<DocumentId> initialDocumentIds = getInitialDiadocDocumentIds(document);
universalTransferDocumentAttachmentBuilder.addAllInitialDocumentIds(initialDocumentIds);
}
SignedContent.Builder signedContentBuilder = universalTransferDocumentAttachmentBuilder.getSignedContentBuilder();
signedContentBuilder.setContent(ByteString.copyFrom(universalTransferDocumentContent));
signedContentBuilder.setSignature(ByteString.copyFrom(signature));
return universalTransferDocumentMessageBuilder;
}
private Message postInvoiceReceipt(String recieverBoxId, String messageId, String entityId) throws Exception {
SignerProtos.Signer.Builder builder = SignerProtos.Signer.newBuilder();
SignerProtos.SignerDetails signerDetails = SignerProtos.SignerDetails.newBuilder()
.setFirstName(config.getFirstName())
.setPatronymic(config.getPatronymic())
.setSurname(config.getSurname())
.setJobTitle(config.getJobTitle())
.build();
builder.setSignerDetails(signerDetails);
SignerProtos.Signer signer = builder.build();
GeneratedFile generatedFile = diadocApi.GenerateInvoiceDocumentReceiptXml(recieverBoxId, messageId, entityId, signer);
SignedContent.Builder signedContent = SignedContent.newBuilder();
signedContent.setContent(ByteString.copyFrom(generatedFile.getContent()));
signedContent.setSignature(ByteString.copyFrom(CertificateHelper.sign(certificate, generatedFile.getContent())));
MessagePatchToPost.Builder patch = MessagePatchToPost.newBuilder();
patch.setBoxId(recieverBoxId);
patch.setMessageId(messageId);
DiadocMessage_PostApiProtos.ReceiptAttachment.Builder receipt = patch.addReceiptsBuilder();
receipt.setParentEntityId(entityId);
receipt.setSignedContent(signedContent);
DiadocMessage_GetApiProtos.MessagePatch messagePatch = diadocApi.PostMessagePatch(patch.build());
return Message.generate(messagePatch);
}
}
Отредактировано пользователем 29 июля 2019 г. 11:50:34(UTC)
| Причина: Не указана
|