Python Blockchain 简明教程
Python Blockchain - Client Class
Client 类使用内置 Python RSA 算法生成 private 和 public 密钥。有兴趣的读者可以参考 this tutorial 以了解 RSA 的实现。在对象初始化期间,我们创建私钥和公钥,并将它们的值存储在实例变量中。
The Client class generates the private and public keys by using the built-in Python RSA algorithm. The interested reader may refer to this tutorial for the implementation of RSA. During the object initialization, we create private and public keys and store their values in the instance variable.
self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()
请注意,您绝不能丢失您的私钥。为了记录,生成的私钥可以复制到安全的外置存储设备上,或者您也可以简单地在纸上写下它的 ASCII 表示。
Note that you should never lose your private key. For record keeping, the generated private key may be copied on a secured external storage or you may simply write down the ASCII representation of it on a piece of paper.
生成的 public 密钥将用作客户的身份。为此,我们定义一个名为 identity 的属性,它返回公钥的 HEX 表示。
The generated public key will be used as the client’s identity. For this, we define a property called identity that returns the HEX representation of the public key.
@property
def identity(self):
return
binascii.hexlify(self._public_key.exportKey(format='DER'))
.decode('ascii')
identity 对每个客户都是唯一的,并且可以公开。任何人都可以使用此 identity 向您发送虚拟货币,它将添加到您的钱包中。
The identity is unique to each client and can be made publicly available. Anybody would be able to send virtual currency to you using this identity and it will get added to your wallet.
Client 类的完整代码显示如下 -
The full code for the Client class is shown here −
class Client:
def __init__(self):
random = Crypto.Random.new().read
self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()
self._signer = PKCS1_v1_5.new(self._private_key)
@property
def identity(self):
return
binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')
Testing Client
现在,我们将编写代码来说明如何使用 Client 类 -
Now, we will write code that will illustrate how to use the Client class −
Dinesh = Client()
print (Dinesh.identity)
上述代码创建了一个 Client 实例,并将其赋值给变量 Dinesh 。我们通过调用其 identity 方法来打印 Dinesh 的公钥。输出如下 −
The above code creates an instance of Client and assigns it to the variable Dinesh. We print the public key of Dinesh by calling its identity method. The output is shown here −
30819f300d06092a864886f70d010101050003818d0030818902818100b547fafceeb131e07
0166a6b23fec473cce22c3f55c35ce535b31d4c74754fecd820aa94c1166643a49ea5f49f72
3181ff943eb3fdc5b2cb2db12d21c06c880ccf493e14dd3e93f3a9e175325790004954c34d3
c7bc2ccc9f0eb5332014937f9e49bca9b7856d351a553d9812367dc8f2ac734992a4e6a6ff6
6f347bd411d07f0203010001
现在,让我们继续在下一章中创建一笔交易。
Now, we let us move on to create a transaction in the next chapter.