最近在写python的工具, 总结一下.
-
type(变量名字)
# 可以打印变量类型,以方便处理 -
len(var)
#可获取类型长度 -
binascii.a2b_hex(string)
# 将十六进制数字字符串转换为二进制数据。该函数也称为unhexlify(string) -
binascii.b2a_hex(string)
python 字符串与16进制互转 -
python 打印对象的所有属性值的方法.
def prn_obj(obj): print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])
以上是打印某个对象的所有属性值的方法
-
pdb 调试
[python调试方法] (https://www.cnblogs.com/skyus/p/7210234.html) -
plain_text.rstrip('\0')
#删除字符串末尾0字符 -
编译protocol Buffers
Now that you have a.proto
, the next thing you need to do is generate the classes you’ll need to read and write AddressBook (and hence Person and PhoneNumber) messages. To do this, you need to run the protocol buffer compiler protoc on your.proto
:
If you haven’t installed the compiler, download the package and follow the instructions in the README.
Now run the compiler, specifying the source directory (where your application’s source code lives – the current directory is used if you don’t provide a value), the destination directory (where you want the generated code to go; often the same as$SRC_DIR
), and the path to your .proto. In this case, you…:
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/addressbook.proto
Because you want Python classes, you use the--python_out
option – similar options are provided for other supported languages.
This generates addressbook_pb2.py in your specified destination directory. -
hashlib.sha256(data)
# 计算data的哈希值>>> import hashlib >>> a = hashlib.sha256('aaaa') >>> a.update('bbbb') #将新的数据和旧的数据一起计算哈希值 >>> a.digest() '\xe5\xc1\xed\xb5\x0f\xf8\xb4\xfc\xc3\xea\xd3\xa8E\xff\xbe\x1a\xd5\x1c\x9d\xae]D3Z\\3;W\xac\x8d\xf0b' >>> b = hashlib.sha256('aaaabbbb') #相同数据对比update的计算哈希值是相同的 >>> b.digest() '\xe5\xc1\xed\xb5\x0f\xf8\xb4\xfc\xc3\xea\xd3\xa8E\xff\xbe\x1a\xd5\x1c\x9d\xae]D3Z\\3;W\xac\x8d\xf0b' >>> b.hexdigest() # 获取十六进制字符串 'e5c1edb50ff8b4fcc3ead3a845ffbe1ad51c9dae5d44335a5c333b57ac8df062'
-
logging 日志级别,网上例子很多
-
python struct模块
解决字节序问题,字节对齐,self.version = struct.unpack('>Q', payload_file.read(8))[0] self.manifest_len = struct.unpack('>Q', payload_file.read(8))[0] self.metadata_signature_len = struct.unpack('>I', payload_file.read(4))[0]
-
用到’openssl’ 这个比较复杂
def _CheckSha256Signature(sig_data, cert_file_name, actual_hash, sig_name): if len(sig_data) != 256: logger.info('%s: signature size (%d) not as expected (256).' % sig_name, len(sig_data)) signed_data, err = RunCommand(['openssl', 'rsautl', '-verify', '-certin', '-inkey', cert_file_name ], send_data=sig_data) if len(signed_data) != len(SIG_ASN1_HEADER) + 32: logger.info('%s: unexpected signed data length (%d).', sig_name, len(signed_data)) if not signed_data.startswith(SIG_ASN1_HEADER): logger.info('%s: not containing standard ASN.1 prefix.', sig_name) signed_hash = signed_data[len(SIG_ASN1_HEADER):] if signed_hash != actual_hash: logger.info('%s: signed hash (%s) different from actual (%s).', sig_name, signed_hash.encode('base64').strip(),
直接输入
openssl x509 -in ca.crt -pubkey
的确会看到两个公钥输出,
如果将它转换成der格式文件的公钥文件,则没有任何多余输出
openssl x509 -in ca.crt -inform PEM -out ca.der -outform DER
提取公钥
openssl x509 -in out/otacert -pubkey -noout > pubkey.pem
/使用公钥进行验证/
$ openssl rsautl -verify -in sign1.txt -inkey pub.pem -pubin -out replain1.txt
/使用私钥进行签名/
$ openssl rsautl -sign -in plain.txt -inkey pri.pem -out sign1.txt
公钥加密
openssl rsautl -encrypt -inkey publickey.pem -pubin -in key.bin -out key.bin.en
将kpcs8 转换到.pem 私钥
openssl pkcs8 -inform DER -nocrypt -in testkey.pk8 -out testkey.pem
直接使用证书进行验签,实际也是使用公钥
openssl rsautl -verify -certin -inkey out/otacert -in old_data -out replain.txt
使用 openssl 生成证书(含openssl详解)
https://blog.csdn.net/gengxiaoming7/article/details/78505107 -
AES128 对称加密
AES加密算法的详细介绍与实现 -
subprocess模块
def RunCommand(command, send_data = None): logger.info('Running command, please wait....') logger.debug('command: %s', command) child = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: result, err = child.communicate(input = send_data)#利用管道输入数据. 和返回数据 finally: exit_code = child.wait() if exit_code: raise RuntimeError('Subprocess %r failed with code %r.' % (command, exit_code)) return result, exit_code
-
import argparse 模块
import argparse parser=argparse.ArgumentParser() parser.add_argument("echo",help="echo the string") args=parser.parse_args() print args.echo
-
填充字符串
from binascii import b2a_hex, a2b_hex h = 'AAA' print b2a_hex(he.ljust(16, '\000')) #output: 41414100000000000000000000000000
(注意): 这里的'\000'
是转义字符, ascii中代表NUL, 和字符’\0’, 是两个东西. 下面是部分ASCII表
Dec Hex | Dec Hex | Dec Hex | Dec Hex | Dec Hex | Dec Hex | Dec Hex | Dec Hex |
---|---|---|---|---|---|---|---|
0 00 NUL | 16 10 DLE | 32 20 空格 | 48 30 0 | 64 40 @ | 80 50 P | 96 60 ` | 112 70 p |
1 01 SOH | 17 11 DC1 | 33 21 ! | 49 31 1 | 65 41 A | 81 51 Q | 97 61 a | 113 71 q |
2 02 STX | 18 12 DC2 | 34 22 " | 50 32 2 | 66 42 B | 82 52 R | 98 62 b | 114 72 r |