Skip to content

Instantly share code, notes, and snippets.

@zshanabek
Created April 6, 2025 10:07
Show Gist options
  • Save zshanabek/3a349b76e408333f02b2d19fefed0a4f to your computer and use it in GitHub Desktop.
Save zshanabek/3a349b76e408333f02b2d19fefed0a4f to your computer and use it in GitHub Desktop.
Helper class in Python for handling cryptographic CMS messages and certificates. Works good for Kazakhtan NCA Certificates.
import base64
import datetime
from asn1crypto import cms
from fastapi import HTTPException, status
class CryptoMixin:
"""
Helper class for handling cryptographic CMS messages and certificates.
"""
def _get_signed_data(self, encoded_cms_data: str) -> cms.SignedData:
"""Decodes CMS data and extracts signed content."""
try:
cms_data = base64.b64decode(encoded_cms_data)
content_info = cms.ContentInfo.load(cms_data)
signed_data = content_info['content']
return signed_data
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid CMS data: {str(e)}")
def get_iins_from_cms(self, encoded_cms_data: str) -> set[str]:
"""Extracts IINs from the CMS data."""
certificates = self._get_signed_data(encoded_cms_data)['certificates']
iins = set()
for certificate in certificates:
cert = certificate.parse()
subject = cert['tbs_certificate']['subject']
iin = subject.native['serial_number'][3:]
iins.add(iin)
return iins
def get_bins_from_cms(self, encoded_cms_data: str) -> str:
"""Extracts BINs (Business Identification Number) from the certificate."""
certificates = self._get_signed_data(encoded_cms_data)['certificates']
bins = set()
for certificate in certificates:
cert = certificate.parse()
subject = cert['tbs_certificate']['subject']
bin = subject.native['organizational_unit_name'][3:]
bins.add(bin)
return bins
def check_cms_expiration_date(self, encoded_cms_data: str) -> None:
"""Checks if the certificate inside CMS data is expired."""
certificates = self._get_signed_data(encoded_cms_data)['certificates']
for certificate in certificates:
cert = certificate.parse()
validity = cert['tbs_certificate']['validity']
not_after = validity['not_after'].native
current_time = datetime.datetime.now(datetime.timezone.utc)
if not_after < current_time:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail=f"Certificate has expired: {not_after}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment