Ошибка при цифровой подписи на нескольких страницах PDF-файла с использованием Endesive PythonPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка при цифровой подписи на нескольких страницах PDF-файла с использованием Endesive Python

Сообщение Anonymous »

Я пытаюсь подписать PDF-документ цифровой подписью с помощью USB-токена класса 3, выполнив поиск на странице по конкретному тексту «Уполномоченное лицо». Это работает отлично, когда мне нужно подписать PDF-файл один раз. Но в одном сценарии я столкнулся с многостраничным документом, в котором мне нужно подписать каждую страницу, после подписания PDF-файла, когда я пытался проверить подписи в Adobe PDF Reader, он подтвердил только мою первую подпись, как показано на снимке экрана ниже< /p>
Изображение

И мне не удалось увидеть аннотации второй и третьей страницы.
Вот мой код,

Код: Выделить всё

def post(self, request):
serializer = PDFSignSerializer(data=request.data)
if serializer.is_valid():
data = serializer.validated_data.get('pdf_base64')

try:
pdf_data = base64.b64decode(data)
except Exception as e:
return Response({'error': f'Failed to decode base64 PDF data: {e}'}, status=status.HTTP_400_BAD_REQUEST)

# Search for text in the PDF and retrieve coordinates
text_to_find = 'Authorised Signatory'  # Text to search for (modify as needed)
text_positions = self.find_text_in_pdf(pdf_data, text_to_find)

if not text_positions:
return Response({'error': 'No position found for signature'}, status=status.HTTP_400_BAD_REQUEST)

# Get the current UTC time using timezone-aware objects
current_utc_time = datetime.datetime.now(datetime.timezone.utc)

# Calculate the Indian time by adding the UTC offset of +5:30
indian_time = current_utc_time + datetime.timedelta(hours=5, minutes=30)

# Format the Indian time string in 24-hour format
indian_time_str = indian_time.strftime('%Y-%m-%d %H:%M:%S') + ' UTC+5:30'

# Initialize the signer
#In above code the settings.DLLPATH is the path of the file - eps2003csp11v2.dll in windows OS
clshsm = Signer(settings.DLLPATH)  # Adjust this according to your settings

# Prepare signing data structure
date = indian_time - datetime.timedelta(hours=11)
date = date.strftime('%Y%m%d%H%M%S+00\'00\'')
dct = {
"sigflags": 3,
"sigbutton": True,
"contact": f'Digitally signed\nDate: {indian_time_str}',
"location": 'India',
"signingdate": date.encode(),
"reason": 'Approved',
"text": {
'wraptext': True,
'fontsize': 6,
'textalign': 'left',
'linespacing': 1,
},
"signature_appearance": {
'background': r'C:\Users\Guest\Downloads\check_mark.png',
'labels': False,
'display': 'contact'.split(','),
},
}

for position in text_positions:
try:
# Reload the PDF document to avoid xref table issues
signed_pdf_data = pdf_data

dct["sigpage"] = position['page_number']
dct["signaturebox"] = (
position['x0'] - 10,
position['page_height'] - position['y0'],
position['x1'] + 10,
position['page_height'] - position['y0'] + 60
)

signed_pdf_data = pdf.cms.sign(signed_pdf_data, dct, None, None, [], 'sha256', clshsm)
pdf_data = pdf_data + signed_pdf_data
# Return the signed PDF data after each signing operation

print(base64.b64encode(pdf_data).decode())

except Exception as e:
return Response({'error': f'Failed to sign at position {position}: {e}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# Prepare response
response_data = {
'message': 'PDF signed successfully.',
'signed_pdf_base64':  base64.b64encode(pdf_data).decode()
}
return Response(response_data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
дополнительно код класса подписывающего лица:

Код: Выделить всё

class Signer(hsm.HSM):
def certificate(self):
self.login("Token", "password")
keyid = [0x5e, 0x9a, 0x33, 0x44, 0x8b, 0xc3, 0xa1, 0x35, 0x33, 0xc7, 0xc2, 0x02, 0xf6, 0x9b, 0xde, 0x55, 0xfe, 0x83, 0x7b, 0xde]
keyid = bytes(keyid)
try:
pk11objects = self.session.findObjects([(PK11.CKA_CLASS, PK11.CKO_CERTIFICATE)])
all_attributes = [
PK11.CKA_VALUE,
PK11.CKA_ID,
]

for pk11object in pk11objects:
try:
attributes = self.session.getAttributeValue(pk11object, all_attributes)
except PK11.PyKCS11Error as e:
continue

attrDict = dict(list(zip(all_attributes, attributes)))
cert = bytes(attrDict[PK11.CKA_VALUE])
return bytes(attrDict[PK11.CKA_ID]), cert
finally:
self.logout()
return None, None

def sign(self, keyid, data, mech):
self.login("Token", "password")
try:
privKey = self.session.findObjects([(PK11.CKA_CLASS, PK11.CKO_PRIVATE_KEY)])[0]
mech = getattr(PK11, 'CKM_%s_RSA_PKCS' % mech.upper())
sig = self.session.sign(privKey, data, PK11.Mechanism(mech, None))
return bytes(sig)
finally:
self.logout()
Где я делаю ошибку?

Подробнее здесь: https://stackoverflow.com/questions/785 ... n-endesive
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»