本文整理汇总了Python中pyelliptic.openssl.OpenSSL.rand方法的典型用法代码示例。如果您正苦于以下问题:Python OpenSSL.rand方法的具体用法?Python OpenSSL.rand怎么用?Python OpenSSL.rand使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyelliptic.openssl.OpenSSL
的用法示例。
在下文中一共展示了OpenSSL.rand方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rand
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def test_rand(self):
"Test basic random number generator correctness"
# There's no way to check if this really is random (it's an
# algorithmic prng). Still, check for common mistakes.
data1 = OpenSSL.rand(10)
data2 = OpenSSL.rand(10)
self.assertNotEqual(data1, data2)
blob = OpenSSL.rand(64000)
stat_zero = [0] * 8
stat_one = [0] * 8
for byte in blob:
byte = ord(byte)
for i in range(8):
bit = byte % 2
byte = byte >> 1
if bit:
stat_one[i] += 1
else:
stat_zero[i] += 1
for i in range(8):
diff = float(abs(stat_zero[i] - stat_one[i]))
# Probabilistic test can sometimes fail, but it should be VERY rare.
# Result is usually < 500, 0.04 sets limit at a value 1280
self.assertTrue(diff / stat_zero[i] < 0.04 * stat_zero[i])
示例2: _encdec
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def _encdec(self, ciphername, msg=None, key=None, iv=None):
"Helper: Encrypt, then decrypt random message"
block_size = pyelliptic.Cipher.get_blocksize(ciphername)
key_size = pyelliptic.Cipher.get_keysize(ciphername)
# Generate IV, key and random message
if key is None:
key = OpenSSL.rand(key_size)
if iv is None:
iv = pyelliptic.Cipher.gen_IV(ciphername)
if msg is None:
msg = OpenSSL.rand(block_size)
self.assertEqual(len(iv), block_size)
self.assertEqual(len(key), key_size)
self.assertEqual(len(msg), block_size)
# Create ciphers
enc_ctx = pyelliptic.Cipher(key=key, iv=iv,
do=pyelliptic.Cipher.ENCRYPT,
ciphername=ciphername,
padding=False)
dec_ctx = pyelliptic.Cipher(key, iv,
pyelliptic.Cipher.DECRYPT,
ciphername=ciphername,
padding=False)
# Encrypt with a bit mangled case.
ciphertext = enc_ctx.update(msg[:10])
ciphertext += enc_ctx.update('')
ciphertext += enc_ctx.update(msg[10:])
ciphertext += enc_ctx.update('')
ciphertext += enc_ctx.final()
self.assertEqual(len(msg), block_size)
self.assertEqual(len(ciphertext), block_size)
# Result must be of length n*blocksize
self.assertEqual(len(ciphertext) % block_size, 0, msg="ciphertext has invalid length")
self.assertEqual(len(ciphertext), len(msg),
msg="ciphertext length does not equal msg length and no padding is enabled")
# Decrypt
cleartext = dec_ctx.ciphering(ciphertext)
self.assertEqual(msg, cleartext)
self.assertNotEqual(msg, ciphertext)
return msg, ciphertext
示例3: pbkdf2
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def pbkdf2(password, salt=None, i=10000, keylen=64):
if salt is None:
salt = OpenSSL.rand(8)
p_password = OpenSSL.malloc(password, len(password))
p_salt = OpenSSL.malloc(salt, len(salt))
output = OpenSSL.malloc(0, keylen)
OpenSSL.PKCS5_PBKDF2_HMAC(p_password, len(password), p_salt,
len(p_salt), i, OpenSSL.EVP_sha256(),
keylen, output)
return salt, output.raw
示例4: raw_encrypt
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def raw_encrypt(data, pubkey_x, pubkey_y, curve='sect283r1',
ephemcurve=None, ciphername='aes-256-cbc'):
if ephemcurve is None:
ephemcurve = curve
ephem = ECC(curve=ephemcurve)
key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
pubkey = ephem.get_pubkey()
iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
ctx = Cipher(key_e, iv, 1, ciphername)
ciphertext = ctx.ciphering(data)
mac = hmac_sha256(key_m, ciphertext)
return iv + pubkey + ciphertext + mac
示例5: raw_encrypt
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def raw_encrypt(data, pubkey_x, pubkey_y, curve="sect283r1", ephemcurve=None, ciphername="aes-256-cbc"):
if ephemcurve is None:
ephemcurve = curve
ephem = ECC(curve=ephemcurve)
key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
pubkey = ephem.get_pubkey()
iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
ctx = Cipher(key_e, iv, 1, ciphername)
ciphertext = ctx.ciphering(data)
# ciphertext = iv + pubkey + ctx.ciphering(data) # We will switch to this line after an upgrade period
mac = hmac_sha256(key_m, ciphertext)
return iv + pubkey + ciphertext + mac
示例6: sendMessage
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def sendMessage(toAddress, subject, message):
if len(shared.myAddressesByTag) == 0:
generateNewAddress()
fromAddress = getCurrentAddress()
status, addressVersionNumber, streamNumber, toRipe = addresses.decodeAddress(toAddress)
ackdata = OpenSSL.rand(32)
TTL = 4*24*60*60
t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int(time.time()), int(time.time()), 0, 'msgqueued', 0, 'sent', 2, TTL)
helper_sent.insert(t)
shared.workerQueue.put(('sendmessage', toAddress))
return ackdata
示例7: send
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def send(self):
status, addressVersionNumber, streamNumber, ripe = decodeAddress(self.toAddress)
ackdata = OpenSSL.rand(32)
t = ()
sqlExecute(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
'',
self.toAddress,
ripe,
self.fromAddress,
self.subject,
self.message,
ackdata,
int(time.time()), # sentTime (this will never change)
int(time.time()), # lastActionTime
0, # sleepTill time. This will get set when the POW gets done.
'msgqueued',
0, # retryNumber
'sent', # folder
2, # encodingtype
min(shared.config.getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days
)
shared.workerQueue.put(('sendmessage', self.toAddress))
示例8: raw_encrypt
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def raw_encrypt(data, pubkey_x, pubkey_y, curve="sect283r1", ephemcurve=None, ciphername="aes-256-cbc"):
if ephemcurve is None:
ephemcurve = curve
ephem = ECC(curve=ephemcurve)
key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
key_e, key_m = key[:32], key[32:]
pubkey = ephem.get_pubkey()
iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
ctx = Cipher(key_e, iv, 1, ciphername)
import time
if int(time.time()) < 1416175200: # Sun, 16 Nov 2014 22:00:00 GMT
ciphertext = ctx.ciphering(data)
else:
ciphertext = (
iv + pubkey + ctx.ciphering(data)
) # Everyone should be using this line after the Bitmessage protocol v3 upgrade period
mac = hmac_sha256(key_m, ciphertext)
if int(time.time()) < 1416175200: # Sun, 16 Nov 2014 22:00:00 GMT
return iv + pubkey + ciphertext + mac
else:
return (
ciphertext + mac
) # Everyone should be using this line after the Bitmessage protocol v3 upgrade period
示例9: send
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def send(self):
status, addressVersionNumber, streamNumber, ripe = decodeAddress(self.toAddress)
ackdata = OpenSSL.rand(32)
t = ()
sqlExecute(
"""INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
"",
self.toAddress,
ripe,
self.fromAddress,
self.subject,
self.message,
ackdata,
int(time.time()), # sentTime (this will never change)
int(time.time()), # lastActionTime
0, # sleepTill time. This will get set when the POW gets done.
"msgqueued",
0, # retryNumber
"sent", # folder
2, # encodingtype
shared.config.getint("bitmessagesettings", "ttl"),
)
shared.workerQueue.put(("sendmessage", self.toAddress))
示例10: run
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def run(self):
while shared.shutdown == 0:
queueValue = shared.addressGeneratorQueue.get()
nonceTrialsPerByte = 0
payloadLengthExtraBytes = 0
if queueValue[0] == 'createChan':
command, addressVersionNumber, streamNumber, label, deterministicPassphrase = queueValue
eighteenByteRipe = False
numberOfAddressesToMake = 1
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
elif queueValue[0] == 'joinChan':
command, chanAddress, label, deterministicPassphrase = queueValue
eighteenByteRipe = False
addressVersionNumber = decodeAddress(chanAddress)[1]
streamNumber = decodeAddress(chanAddress)[2]
numberOfAddressesToMake = 1
numberOfNullBytesDemandedOnFrontOfRipeHash = 1
elif len(queueValue) == 7:
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue
try:
numberOfNullBytesDemandedOnFrontOfRipeHash = shared.config.getint(
'bitmessagesettings', 'numberofnullbytesonaddress')
except:
if eighteenByteRipe:
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
else:
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # The default
elif len(queueValue) == 9:
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue
try:
numberOfNullBytesDemandedOnFrontOfRipeHash = shared.config.getint(
'bitmessagesettings', 'numberofnullbytesonaddress')
except:
if eighteenByteRipe:
numberOfNullBytesDemandedOnFrontOfRipeHash = 2
else:
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 # The default
elif queueValue[0] == 'stopThread':
break
else:
sys.stderr.write('Programming error: A structure with the wrong ' +
'number of values was passed into the addressGeneratorQueue. ' +
'Here is the queueValue: %s\n' % repr(queueValue))
if addressVersionNumber < 3 or addressVersionNumber > 4:
sys.stderr.write(
'Program error: For some reason the address generator queue has ' +
'been given a request to create at least one version %s address ' +
'which it cannot do.\n' % addressVersionNumber)
if nonceTrialsPerByte == 0:
nonceTrialsPerByte = shared.config.getint(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes == 0:
payloadLengthExtraBytes = shared.config.getint(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
if command == 'createRandomAddress':
shared.UISignalQueue.put(('updateStatusBar',
tr._translate("MainWindow",
"Generating one new address")))
# This next section is a little bit strange. We're going to generate keys over and over until we
# find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address,
# we won't store the \x00 or \x00\x00 bytes thus making the
# address shorter.
startTime = time.time()
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
potentialPrivSigningKey = OpenSSL.rand(32)
potentialPubSigningKey = highlevelcrypto.pointMult(potentialPrivSigningKey)
while True:
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
potentialPrivEncryptionKey = OpenSSL.rand(32)
potentialPubEncryptionKey = highlevelcrypto.pointMult(
potentialPrivEncryptionKey)
ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha512')
sha.update(
potentialPubSigningKey + potentialPubEncryptionKey)
ripe.update(sha.digest())
if ripe.digest()[:numberOfNullBytesDemandedOnFrontOfRipeHash] == '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash:
break
logger.info('Generated address with ripe digest: %s' % hexlify(ripe.digest()))
try:
logger.info('Address generator calculated %s addresses at %s addresses per second before finding one with the correct ripe-prefix.' % (numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime)))
except ZeroDivisionError:
# The user must have a pretty fast computer. time.time() - startTime equaled zero.
pass
address = encodeAddress(addressVersionNumber, streamNumber, ripe.digest())
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80' + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256(
privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58)
privEncryptionKey = '\x80' + potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256(
#.........这里部分代码省略.........
示例11: gen_IV
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def gen_IV(ciphername):
cipher = OpenSSL.get_cipher(ciphername)
return OpenSSL.rand(cipher.get_blocksize())
示例12: run
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def run(self):
while True:
queueValue = shared.addressGeneratorQueue.get()
nonceTrialsPerByte = 0
payloadLengthExtraBytes = 0
if len(queueValue) == 7:
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue
elif len(queueValue) == 9:
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue
else:
sys.stderr.write(
'Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % queueValue)
if addressVersionNumber < 3 or addressVersionNumber > 3:
sys.stderr.write(
'Program error: For some reason the address generator queue has been given a request to create at least one version %s address which it cannot do.\n' % addressVersionNumber)
if nonceTrialsPerByte == 0:
nonceTrialsPerByte = shared.config.getint(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes == 0:
payloadLengthExtraBytes = shared.config.getint(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
if addressVersionNumber == 3: # currently the only one supported.
if command == 'createRandomAddress':
shared.UISignalQueue.put((
'updateStatusBar', bitmessagemain.translateText("MainWindow", "Generating one new address")))
# This next section is a little bit strange. We're going to generate keys over and over until we
# find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address,
# we won't store the \x00 or \x00\x00 bytes thus making the
# address shorter.
startTime = time.time()
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
potentialPrivSigningKey = OpenSSL.rand(32)
potentialPubSigningKey = pointMult(potentialPrivSigningKey)
while True:
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
potentialPrivEncryptionKey = OpenSSL.rand(32)
potentialPubEncryptionKey = pointMult(
potentialPrivEncryptionKey)
# print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex')
# print 'potentialPubEncryptionKey',
# potentialPubEncryptionKey.encode('hex')
ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha512')
sha.update(
potentialPubSigningKey + potentialPubEncryptionKey)
ripe.update(sha.digest())
# print 'potential ripe.digest',
# ripe.digest().encode('hex')
if eighteenByteRipe:
if ripe.digest()[:2] == '\x00\x00':
break
else:
if ripe.digest()[:1] == '\x00':
break
print 'Generated address with ripe digest:', ripe.digest().encode('hex')
print 'Address generator calculated', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix, 'addresses at', numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix / (time.time() - startTime), 'addresses per second before finding one with the correct ripe-prefix.'
address = encodeAddress(3, streamNumber, ripe.digest())
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80' + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256(
privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58)
# print 'privSigningKeyWIF',privSigningKeyWIF
privEncryptionKey = '\x80' + potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKey).digest()).digest()[0:4]
privEncryptionKeyWIF = arithmetic.changebase(
privEncryptionKey + checksum, 256, 58)
# print 'privEncryptionKeyWIF',privEncryptionKeyWIF
shared.config.add_section(address)
shared.config.set(address, 'label', label)
shared.config.set(address, 'enabled', 'true')
shared.config.set(address, 'decoy', 'false')
shared.config.set(address, 'noncetrialsperbyte', str(
nonceTrialsPerByte))
shared.config.set(address, 'payloadlengthextrabytes', str(
payloadLengthExtraBytes))
shared.config.set(
address, 'privSigningKey', privSigningKeyWIF)
shared.config.set(
address, 'privEncryptionKey', privEncryptionKeyWIF)
with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile)
# It may be the case that this address is being generated
# as a result of a call to the API. Let us put the result
# in the necessary queue.
bitmessagemain.apiAddressGeneratorReturnQueue.put(address)
shared.UISignalQueue.put((
'updateStatusBar', bitmessagemain.translateText("MainWindow", "Done generating address. Doing work necessary to broadcast it...")))
#.........这里部分代码省略.........
示例13: _handle_request
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
#.........这里部分代码省略.........
return 'Trashed sent message (assuming message existed).'
elif method == 'trashSentMessageByAckData':
# This API method should only be used when msgid is not available
if len(params) == 0:
raise APIError(0, 'I need parameters!')
ackdata = self._decode(params[0], "hex")
sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''',
ackdata)
return 'Trashed sent message (assuming message existed).'
elif method == 'sendMessage':
if len(params) == 0:
raise APIError(0, 'I need parameters!')
elif len(params) == 4:
toAddress, fromAddress, subject, message = params
encodingType = 2
elif len(params) == 5:
toAddress, fromAddress, subject, message, encodingType = params
if encodingType != 2:
raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.')
subject = self._decode(subject, "base64")
message = self._decode(message, "base64")
toAddress = addBMIfNotPresent(toAddress)
fromAddress = addBMIfNotPresent(fromAddress)
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(toAddress)
self._verifyAddress(fromAddress)
try:
fromAddressEnabled = shared.config.getboolean(
fromAddress, 'enabled')
except:
raise APIError(13, 'Could not find your fromAddress in the keys.dat file.')
if not fromAddressEnabled:
raise APIError(14, 'Your fromAddress is disabled. Cannot send.')
ackdata = OpenSSL.rand(32)
t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int(
time.time()), 'msgqueued', 1, 1, 'sent', 2)
helper_sent.insert(t)
toLabel = ''
queryreturn = sqlQuery('''select label from addressbook where address=?''', toAddress)
if queryreturn != []:
for row in queryreturn:
toLabel, = row
# apiSignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata)))
shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, toLabel, fromAddress, subject, message, ackdata)))
shared.workerQueue.put(('sendmessage', toAddress))
return ackdata.encode('hex')
elif method == 'sendBroadcast':
if len(params) == 0:
raise APIError(0, 'I need parameters!')
if len(params) == 3:
fromAddress, subject, message = params
encodingType = 2
elif len(params) == 4:
fromAddress, subject, message, encodingType = params
if encodingType != 2:
raise APIError(6, 'The encoding type must be 2 because that is the only one this program currently supports.')
subject = self._decode(subject, "base64")
message = self._decode(message, "base64")
fromAddress = addBMIfNotPresent(fromAddress)
示例14: processmsg
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
#.........这里部分代码省略.........
toLabel = toAddress
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
logger.info('Message subject (first 100 characters): %s' % repr(subject)[:100])
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
logger.info('messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.')
subject = ''
body = ''
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
# Let us make sure that we haven't already received this message
if helper_inbox.isMessageAlreadyInInbox(sigHash):
logger.info('This msg is already in our inbox. Ignoring it.')
blockMessage = True
if not blockMessage:
if messageEncodingType != 0:
t = (inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0, sigHash)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newMessage"])
# Let us now check and see whether our receiving address is
# behaving as a mailing list
if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
try:
mailingListName = shared.config.get(
toAddress, 'mailinglistname')
except:
mailingListName = ''
# Let us send out this message as a broadcast
subject = self.addMailingListNameToSubject(
subject, mailingListName)
# Let us now send this message out as a broadcast
message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime(
)) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body
fromAddress = toAddress # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
ackdataForBroadcast = OpenSSL.rand(
32) # We don't actually need the ackdataForBroadcast for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
toAddress = '[Broadcast subscribers]'
ripe = ''
# We really should have a discussion about how to
# set the TTL for mailing list broadcasts. This is obviously
# hard-coded.
TTL = 2*7*24*60*60 # 2 weeks
t = ('',
toAddress,
ripe,
fromAddress,
subject,
message,
ackdataForBroadcast,
int(time.time()), # sentTime (this doesn't change)
int(time.time()), # lastActionTime
0,
'broadcastqueued',
0,
'sent',
2,
TTL)
helper_sent.insert(t)
shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdataForBroadcast)))
shared.workerQueue.put(('sendbroadcast', ''))
if self.ackDataHasAVaildHeader(ackData):
shared.checkAndShareObjectWithPeers(ackData[24:])
# Display timing data
timeRequiredToAttemptToDecryptMessage = time.time(
) - messageProcessingStartTime
shared.successfullyDecryptMessageTimings.append(
timeRequiredToAttemptToDecryptMessage)
sum = 0
for item in shared.successfullyDecryptMessageTimings:
sum += item
logger.debug('Time to decrypt this message successfully: %s\n\
Average time for all message decryption successes since startup: %s.' %
(timeRequiredToAttemptToDecryptMessage, sum / len(shared.successfullyDecryptMessageTimings))
)
示例15: process_message
# 需要导入模块: from pyelliptic.openssl import OpenSSL [as 别名]
# 或者: from pyelliptic.openssl.OpenSSL import rand [as 别名]
def process_message(self, peer, fromAddress, rcpttos, data):
#print("Peer", peer)
#print("Mail From", fromAddress)
#print("Rcpt To", rcpttos)
#print("Data")
#print(data)
#print('--------')
#print(type(fromAddress))
message = parser.Parser().parsestr(data)
message['X-Bitmessage-Sending-Version'] = shared.softwareVersion
message['X-Bitmessage-Flags'] = '0'
bitmessageSMTPServer.stripMessageHeaders(message)
fp = StringIO()
gen = generator.Generator(fp, mangle_from_=False, maxheaderlen=128)
gen.flatten(message)
message_as_text = fp.getvalue()
with shared.printLock:
print(message_as_text)
checksum = hashlib.sha256(message_as_text).digest()[:2]
checksum = (ord(checksum[0]) << 8) | ord(checksum[1])
# Determine the fromAddress and make sure it's an owned identity
if not (fromAddress.startswith('BM-') and '.' not in fromAddress):
raise Exception("From Address must be a Bitmessage address.")
else:
status, addressVersionNumber, streamNumber, fromRipe = decodeAddress(fromAddress)
if status != 'success':
with shared.printLock:
print 'Error: Could not decode address: ' + fromAddress + ' : ' + status
if status == 'checksumfailed':
print 'Error: Checksum failed for address: ' + fromAddress
if status == 'invalidcharacters':
print 'Error: Invalid characters in address: ' + fromAddress
if status == 'versiontoohigh':
print 'Error: Address version number too high (or zero) in address: ' + fromAddress
raise Exception("Invalid Bitmessage address: {}".format(fromAddress))
#fromAddress = addBMIfNotPresent(fromAddress) # I know there's a BM-, because it's required when using SMTP
try:
fromAddressEnabled = shared.config.getboolean(fromAddress, 'enabled')
except:
with shared.printLock:
print 'Error: Could not find your fromAddress in the keys.dat file.'
raise Exception("Could not find address in keys.dat: {}".format(fromAddress))
if not fromAddressEnabled:
with shared.printLock:
print 'Error: Your fromAddress is disabled. Cannot send.'
raise Exception("The fromAddress is disabled: {}".format(fromAddress))
for recipient in rcpttos:
toAddress, _ = recipient.split('@', 1)
if not (toAddress.startswith('BM-') and '.' not in toAddress):
# TODO - deliver message to another SMTP server..
# I think this feature would urge adoption: the ability to use the same bitmessage address
# for delivering standard E-mail as well bitmessages.
raise Exception("Cannot yet handle normal E-mail addresses.")
else:
# This is now the 3rd copy of this message delivery code.
# There's one in the API, there's another copy in __init__ for
# the UI. Yet another exists here. It needs to be refactored
# into a utility func!
status, addressVersionNumber, streamNumber, toRipe = decodeAddress(toAddress)
if status != 'success':
with shared.printLock:
print 'Error: Could not decode address: ' + toAddress + ' : ' + status
if status == 'checksumfailed':
print 'Error: Checksum failed for address: ' + toAddress
if status == 'invalidcharacters':
print 'Error: Invalid characters in address: ' + toAddress
if status == 'versiontoohigh':
print 'Error: Address version number too high (or zero) in address: ' + toAddress
raise Exception("Invalid Bitmessage address: {}".format(toAddress))
toAddressIsOK = False
try:
shared.config.get(toAddress, 'enabled')
except:
toAddressIsOK = True
if not toAddressIsOK:
# The toAddress is one owned by me. We cannot send
# messages to ourselves without significant changes
# to the codebase.
with shared.printLock:
print "Error: One of the addresses to which you are sending a message, {}, is yours. Unfortunately the Bitmessage client cannot process its own messages. Please try running a second client on a different computer or within a VM.".format(toAddress)
raise Exception("An address that you are sending a message to, {}, is yours. Unfortunately the Bitmessage client cannot process its own messages. Please try running a second client on a different computer or within a VM.".format(toAddress))
# The subject is specially formatted to identify it from non-E-mail messages.
# TODO - The bitfield will be used to convey things like external attachments, etc.
# Last 2 bytes are two bytes of the sha256 checksum of message
if 'Subject' in message:
subject = message['Subject']
else:
subject = ''
ackdata = OpenSSL.rand(32)
#.........这里部分代码省略.........