python使用ctypes调用国密SDF库实现加解密

简介

直接上代码,简单实现了python同过ctypes调用SDF库。
主要实现一下功能,其他功能可自行扩展。

  1. 加载SDF库
  2. 打开设备
  3. 打开会话
  4. 导入临时密钥,获取临时密钥句柄
  5. SM1加密
  6. SM1解密
  7. 关闭会话
  8. 关闭设备
from ctypes import *  
import binascii, sys, thread, time, threading, copy

SGD_SM1_ECB = 0x00000101
SGD_SM1_CBC = 0x00000102
algoid = SGD_SM1_ECB

fileName = "./yoursdf.dll"
pdll = cdll.LoadLibrary(fileName)

pDev = c_void_p(None)
ppDev = pointer(pDev)
rv = pdll.SDF_OpenDevice(ppDev)

if(rv!=0):
	print('SDF_OpenDevice error. return '+hex(rv))

pSess = c_void_p(None)
ppSess = pointer(pSess)

rv = pdll.SDF_OpenSession(pDev, ppSess)
if(rv!=0):
	print('SDF_OpenSession error. return '+hex(rv))
	
pKey = c_void_p(None)
ppKey = pointer(pKey)

keybuf = (c_byte * 16)()
for i in range(16):
	keybuf[i] = i
	
ivbuf = (c_byte * 16)()
for i in range(16):
	ivbuf[i] = i
	
rv = pdll.SDF_ImportKey(pSess, keybuf, len(keybuf), ppKey)
if(rv!=0):
	print('SDF_ImportKey error. return '+hex(rv))
	os.exit(0)

plainbuf = (c_byte * 16)()
for i in range(16):
	plainbuf[i] = 0xff

cipherbuf = (c_byte * 2048)()
cipherlen = c_int(2048)

rv = pdll.SDF_Encrypt( pSess, pKey, algoid, ivbuf, plainbuf, 16, cipherbuf, pointer(cipherlen));
if(rv!=0):
	print('SDF_Encrypt_Dvs error. return '+hex(rv))	
	os.exit(0)

result = binascii.hexlify(b''.join(chr(s&0xff) for s in cipherbuf[0:16]))

outstr = ''.join(result)
outstr = outstr.upper()
print(outstr)

'''
for i in range(0, cipherlen.value):
	plainbuf[i] = cipherbuf[i]
'''
plainbuf = copy.copy(cipherbuf)

rv = pdll.SDF_Decrypt( pSess, pKey, algoid, ivbuf, plainbuf, 16, cipherbuf, pointer(cipherlen));
if(rv!=0):
	print('SDF_Encrypt_Dvs error. return '+hex(rv))	
	os.exit(0)

result = binascii.hexlify(b''.join(chr(s&0xff) for s in cipherbuf[0:16]))

outstr = ''.join(result)
outstr = outstr.upper()
print(outstr)

pdll.SDF_OpenSession(pSess)
pdll.SDF_CloseDevice(pDev)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

化妖成魔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值