简介
直接上代码,简单实现了python同过ctypes调用SDF库。
主要实现一下功能,其他功能可自行扩展。
- 加载SDF库
- 打开设备
- 打开会话
- 导入临时密钥,获取临时密钥句柄
- SM1加密
- SM1解密
- 关闭会话
- 关闭设备
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)