MD5:
不安全的加密方法
import hashlib
m = hashlib.md5()
m.update("使用md5加密的数据".encode("utf-8"))
print(m.hexdigest())
SHA:
目前相对安全的加密方法
import hashlib
s= hashlib.sha256()
s.update("使用sha256加密的数据".encode("utf-8"))
print(s.hexdigest())
Base64:
把任意二进制数据表示成64个字符。
可进行编码解码
data = '你好,区块链'
result = base64.b64encode(data.encode("utf-8"))
print(result)
text = base64.b64decode(result)
print(text.decode("utf-8"))
ECC:
在网络安全课上学到的感觉最难理解的加密方法,过两天要好好看一下椭圆加密算法的原理。
Python中使用这种模块需要装ESDSA
from ecdsa import SigningKey, SECP256k1
sk = SigningKey.generate(curve=SECP256k1)
vk = sk.get_verifying_key()
signature = sk.sign("Something".encode("utf-8"))
vk.verify(signature,"Something".encode("utf-8"))
#最后能输出true
绘图:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2* np.pi,50)#linspace生成一系列点
plt.plot(x,np.sin(x))#plot接收一些列x,y
plt.show()
简化的区块链区块定义:
包括父区块的哈希值、数据、时间戳、哈希值这四个字段。区块的哈希值由其中父区块哈希值、数据和时间戳3个字段拼接起来通过哈希算法产生。
import hashlib
from datetime import datetime
class Block:
def __init__(self,data,prev_hash):
self.prev_hash = prev_hash
self.data = data
self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message = hashlib.sha256()
message.update(str(self.prev_hash).encode("utf-8"))
message.update(str(self.data).encode('utf-8'))
message.update(str(self.timestamp).encode('utf-8'))
self.hash = message.hexdigest()
定义区块结构后还需要定义一个区块链的结构.区块链的包括一个数组,以及将区块入链的函数
class BlockChain:
def __init__(self):
self.blocks= []
def add_block(self,block):
self.blocks.append(block)
然后定义第一个块,称为创世区块,没有父哈希值
genesis_block = Block(data="创世区块",prev_hash=" ")
再随意创建几个区块
new_block = Block(data="张三转给李四1个比特币",prev_hash=genesis_block.hash)
new_block2 = Block(data="张三转给王五2个比特币",prev_hash=new_block.hash)
然后创建一条区块链,将以上创建的几个区块入链即可。
blockchain = BlockChain()
blockchain.add_block(genesis_block)
blockchain.add_block(new_block)
blockchain.add_block(new_block2)
显示结果
print("区块链包含区块个数:%d\n" % len(blockchain.blocks))
for block in blockchain.blocks:
print("父区区块哈希值:%s" % block.prev_hash)
print("区块内容:%s" % block.data)
print("区块哈希:%s" % block.hash)
print("\n")