Пример #1
0
def protocol(P, G):
    a = get_random_key(P)
    b = get_random_key(P)

    fake_A = G
    fake_B = G

    private_A = get_key(fake_B, a, P)
    private_B = get_key(fake_A, b, P)

    def sha(s):
        return sha1(hex(int(s))).digest()[0:16]

    AES_A = sha(private_A)
    msg_A = 'hi, B'
    cipher_A = aes.encryptData(AES_A, msg_A)

    AES_M = sha(0)
    msg_AM = aes.decryptData(AES_M, cipher_A)
    assert msg_AM == msg_A

    AES_B = sha(private_B)
    msg_B = aes.decryptData(AES_B, cipher_A)
    cipher_B = aes.encryptData(AES_B, msg_B)

    msg_BM = aes.decryptData(AES_M, cipher_B)

    assert msg_BM == msg_A
    assert AES_M == AES_A
Пример #2
0
def create_acc():
	if request.form['password'] == request.form['confirm-password']:
		pwd = request.form['password']
		if len(pwd) > 6:
		  log("INFO", "Password is good")
		else:
			problem = "Password is shorter than 7 characters"
		  	return render_template('problem.html', problem = problem)
		pwd = essence.passToAesKey(pwd)
		essence.pub, essence.priv, essence.params, essence.g = essence.n.generateNTRUKeysAlpha()
		log('Public Key', essence.pub)
		essence.pub = base64.b64encode('%s|%s' % (essence.pub, str(essence.params).replace(' ', '')))
		log("INFO", "Your generated public key is Ex%s" % essence.pub)
		f = open('keys/pub.key' , 'w+')
		f.write(essence.pub)
		f.close()
		log('Params', str(essence.params))
		f = open('keys/priv.key' , 'w+')
		f.write(base64.b64encode(aes.encryptData(pwd, str(essence.priv))))
		f.close()
		f = open('keys/g.txt' , 'w+')
		f.write(base64.b64encode(aes.encryptData(pwd, str(essence.g))))
		f.close()
		f = open('contacts.py' , 'w+')
		f.write('contacts = {\'Me\' : \'Ex%s\'}' % essence.pub)
		f.close()
		contacts = {'Me' : essence.pub}
		log('INFO', 'Your Essence account is ready for use.')
		return render_template('login.html', pubkey=essence.pub)
Пример #3
0
def mkbackup(wallet, pw):
    seed = getseed(wallet['encseed'], pw, wallet['ethaddr'])
    return {
        "withpw": aes.encryptData(pw, seed).encode('hex'),
        "withwallet": aes.encryptData(wallet['bkp'], seed).encode('hex'),
        "ethaddr": wallet['ethaddr']
    }
Пример #4
0
def mkbackup(wallet,pw):
    seed = getseed(wallet['encseed'],pw,wallet['ethaddr'])
    return {
        "withpw": aes.encryptData(pbkdf2(pw),seed).encode('hex'),
        "withwallet": aes.encryptData(pbkdf2(wallet['bkp']),seed).encode('hex'),
        "ethaddr": wallet['ethaddr']
    }
Пример #5
0
def upload_to_dropbox(backupConfig, backupArchive):
    print("Login to dropbox...")
    try:
        try:
            from dropbox import client, rest, session
        except ImportError, e:
            print("Dropbox sdk not found, please download and install the \
            latest dropbox sdk from https://www.dropbox.com/developers/reference/sdk"
                  )
            raise e
        sess = session.DropboxSession(backupConfig.dropboxAppKey,
                                      backupConfig.dropboxAppSecret,
                                      backupConfig.dropboxAccessType)
        if backupConfig.dropboxAccessToken == gEmptyStr or not backupConfig.dropboxAccessToken:
            requestToken = sess.obtain_request_token()
            url = sess.build_authorize_url(requestToken)
            # Make the user sign in and authorize this token
            print("url: %s" % url)
            print(
                "Please visit this website and press the 'Allow' button, then hit 'Enter' here."
            )
            raw_input()
            accessToken = sess.obtain_access_token(requestToken)
            # encrypt access token
            dropboxAccessTokenAesKey = aes.generateRandomKey(16)
            accessTokenKey = aes.encryptData(dropboxAccessTokenAesKey,
                                             accessToken.key)
            accessTokenSecret = aes.encryptData(dropboxAccessTokenAesKey,
                                                accessToken.secret)
            backupConfig.configParser.set(
                backupConfig.DropboxSection, "access_token", "%s:%s:%s" %
                (accessTokenKey.encode("hex"), accessTokenSecret.encode("hex"),
                 dropboxAccessTokenAesKey.encode("hex")))
            client = client.DropboxClient(sess)
        else:
            # read access token
            if not backupConfig.dropboxAccessToken or backupConfig.dropboxAccessToken == gEmptyStr:
                raise Exception("Cannot read access_token in config file %s" %
                                backupConfig.configPath)
            accessTokenKey, accessTokenSecret, dropboxAccessTokenAesKey = backupConfig.dropboxAccessToken.split(
                ":")
            accessTokenKey = aes.decryptData(
                binascii.unhexlify(dropboxAccessTokenAesKey),
                binascii.unhexlify(accessTokenKey))
            accessTokenSecret = aes.decryptData(
                binascii.unhexlify(dropboxAccessTokenAesKey),
                binascii.unhexlify(accessTokenSecret))
            sess.set_token(accessTokenKey, accessTokenSecret)
            # init client
            client = client.DropboxClient(sess)
        # send backup file
        with open(backupArchive) as f:
            print("Upload %s to dropbox..." % (backupArchive))
            response = client.put_file(
                "%s/%s" % (backupConfig.dropboxBackupDir,
                           os.path.basename(allBackupArchive)), f)
Пример #6
0
def encryptPassword(key,password,method='aes',keyfile=None):
	if keyfile: key = getKeyFromFile(keyfile,key)
	if not key: return None
	if method.lower() == 'des':
		password = encryptDes(key,password)
	elif method.lower() == 'aes':
		password =  aes.encryptData(hashlib.md5(key).digest(),password)
	else:
		password = encryptDes(key,password)
		password = aes.encryptData(hashlib.md5(key).digest(),password)
		
	return binascii.hexlify(password)
Пример #7
0
def send(message, contact):
    data = config.my_data.find("data", "all")[0]
    target = config.nodes.find("nodes", {"address": contact})[0]
    address = data['address']
    stamp = time.time()
    config.cache.insert("sent", {
        "message": message,
        "contact": contact,
        "time": stamp
    })
    config.cache.save()
    public_key = filter(None, re.findall("[0-9]*", target['publickey'])
                        )  #Safe way of extracting the public key from a string
    public_key = PublicKey(int(public_key[0]),
                           int(public_key[1]))  # Re build public key
    key = uuid.uuid4().hex  # Generate AES key
    k = encrypt(
        key,
        public_key)  #Encrypt the key with the RSA public key of the target
    k = base64.b64encode(k)  #Encode the encrypted data
    message = base64.b64encode(aes.encryptData(
        key,
        message))  #Encrypt the message with the AES key and then encode it
    broadcast.send(
        {
            "cmd": "send_message",
            "message": message,
            "contact": contact,
            "address": address,
            "key": k,
            "time": stamp
        }, False)  #Broadcast the message
Пример #8
0
def send_msg(msg, title, to, addr):
    try:
        data = db.nodes.find("nodes", {"addr":to})[0]
    except:
        return "Address doesn't exist"
    if data['publickey'].startswith("PublicKey(") and data['publickey'].endswith(")"):
       # msg = encrypt(msg, eval(data['publickey'])) <--- Old encryption code
	aeskey = str(uuid.uuid4().hex) # Generate new AES Key
	key = encrypt(aeskey, eval(data['publickey'])) # Encrypt AES key with target's RSA Public Key
	key = base64.b64encode(key) # Base64 encode the key
	msg = aes.encryptData(aeskey,msg) # Encrypt Message with AES Key
        msg = base64.b64encode(msg) # Base64 encode the message
	as_num, as_nonce = antispam.find_antispam(to,addr,msg,antispam.get_required_difficulty(msg))
    else:
        return "Invalid public key for", addr
    id = ""
    while True:
        id = uuid.uuid4().hex
        if db.messages.find("messages", {"id":id}):
            continue
        else:
            break
    print "Sending message ID " + id + " with key " + key
    nodes = db.nodes.find("nodes", "all")
    for x in nodes:
        s = ssl.socket()
        try:
            s.settimeout(1)
            s.connect((x['ip'], x['port']))
            s.send(json.dumps({"cmd":"message", "id":id, "message":msg, "title":title, "to":to, "from":addr,"num":as_num,"nonce":as_nonce,"key":key}))
            s.close()
        except Exception, error:
            db.unsent.insert("unsent", {"to":[x['ip'], x['port']], "message":{"cmd":"message", "id":id, "message":msg, "title":title, "to":to, "from":addr,"num":as_num,"nonce":as_nonce,"key":key}})
Пример #9
0
 def _parse_dropbox(self):
     self.dropboxAccessToken = self.configParser.get(self.DropboxSection, "access_token")
     if self.backupWithDropbox != gEmptyStr and self.backupWithDropbox:
         # get dropbox auth info
         self.dropboxUser = self.configParser.get(self.DropboxSection, "User")
         if self.dropboxUser:
             self.dropboxUser = self.dropboxUser.strip()
         self.dropboxPassStr = self.configParser.get(self.DropboxSection, "Password")
         if self.dropboxPassStr:
             self.dropboxPassStr = self.dropboxPassStr.strip()
         if not self.dropboxUser or gEmptyStr == self.dropboxUser:
             self.dropboxUser = raw_input("Your user name for dropbox: ")
             self.configParser.set(self.DropboxSection, "User", self.dropboxUser)
             self.dropboxPassStr = ""
         if not self.dropboxPassStr or self.dropboxPassStr == gEmptyStr:
             self.dropboxPassStr = getpass.getpass("Your password for dropbox user %s: " % (self.dropboxUser))
             self.dropboxPassKey = aes.generateRandomKey(16)
             # set password with aes encryption
             tmpPass = aes.encryptData(dropboxPassKey, dropboxPassStr)
             self.configParser.set(self.DropboxSection, "Password", tmpPass.encode("hex") + gSepChar + self.dropboxPassKey.encode("hex"))
             # reset access token when username or password changes
             self.dropboxAccessToken = gEmptyStr
         else:
             self.dropboxPass, self.dropboxPassKey = self.dropboxPassStr.split(":")
             self.dropboxPass = aes.decryptData(binascii.unhexlify(self.dropboxPassKey), binascii.unhexlify(self.dropboxPass))
     self.dropboxAppKey = self.configParser.get(self.DropboxSection, "APP_KEY")
     self.dropboxAppSecret = self.configParser.get(self.DropboxSection, "APP_SECRET")
     self.dropboxAccessType = "dropbox"
     self.dropboxBackupDir = self.configParser.get(self.DropboxSection, "target_dir")
     if not self.dropboxBackupDir:
         self.dropboxBackupDir = "/"
     else:
         self.dropboxBackupDir = self.dropboxBackupDir.rstrip("/")
Пример #10
0
def finalize(wallet, unspent, pw):
    seed = getseed(wallet["encseed"], pw, wallet["ethaddr"])
    balance = sum([o["value"] for o in unspent])
    if balance == 0:
        raise Exception("No funds in address")
    if balance < 1000000:
        raise Exception("Insufficient funds. Need at least 0.01 BTC")
    ephem = random_key().decode('hex')
    shared = multiply(our_pubkey, ephem)
    data = aes.encryptData(shared[:16], wallet["email"]) + compress(
        privtopub(ephem))
    data = chr(len(data)) + data
    outs = [
        exodus + ':' + str(balance - 70000),
        hex_to_b58check(wallet["ethaddr"]) + ':10000'
    ]
    while len(data) > 0:
        d = data[:20] + '\x00' * max(0, 20 - len(data))
        outs.append(bin_to_b58check(d) + ':10000')
        data = data[20:]
    tx = mktx(unspent, outs)
    btcpriv = sha3(seed + '\x01')
    for i in range(len(unspent)):
        tx = sign(tx, i, btcpriv)
    return tx
Пример #11
0
	def addKey(self, username, pwd):
		pin = base64.b64encode(aes.encryptData(self.passToAesKey(pwd), '1337'))
		if not self.mysql.where('username', username).select('key').query():
			self.mysql.insert('username', username).query()
			self.mysql.where('username', username).update('key', pin).query()
			return True
		else:
			return False
Пример #12
0
def encrypt(file):
	enc1 = open(file, "r")
        enc = enc1.read()
        key = "\xed\xac\xbe\x88<.\xd9H8D\xb2'\x19\xb9IG"
        ret = aes.encryptData(key, enc, mode=2)
        f = open(file, "w+")
        f.write(ret)
	print("Encrypted: " + file)
Пример #13
0
def encode_privkey(privkey, password):
    '''
    Encode a private key to text.
    '''
    keystring = "CHECK:{0}:{1}:{2}:{3}:{4}".format(privkey.n, privkey.e,
                                                   privkey.d, privkey.p,
                                                   privkey.q)
    return b64encode(aes.encryptData(aes_key(password), keystring))
Пример #14
0
    def write(self):
        if not self.password:
            return

        data = aes.encryptData(hashlib.md5(self.password).hexdigest(), self.data)
        with open(self.file_, "wb") as file:
            file.write(data)
        print "Data saved!"
Пример #15
0
    def write(self):
        if not self.password:
            return

        data = aes.encryptData(
            hashlib.md5(self.password).hexdigest(), self.data)
        with open(self.file_, "wb") as file:
            file.write(data)
        print "Data saved!"
Пример #16
0
def genwallet(seed, pw):
    encseed = aes.encryptData(pw, seed)
    ethpriv = sha3(seed)
    btcpriv = sha3(seed + '\x01')
    ethaddr = sha3(secure_privtopub(ethpriv)[1:])[12:].encode('hex')
    btcaddr = privkey_to_address(btcpriv, magicbyte)
    return {
        "encseed": encseed.encode('hex'),
        "ethaddr": ethaddr,
        "btcaddr": btcaddr
    }
Пример #17
0
def upload_to_dropbox(backupConfig, backupArchive):
    print("Login to dropbox...")
    try:
        try:
            from dropbox import client, rest, session
        except ImportError, e:
            print("Dropbox sdk not found, please download and install the \
            latest dropbox sdk from https://www.dropbox.com/developers/reference/sdk")
            raise e
        sess = session.DropboxSession(backupConfig.dropboxAppKey, backupConfig.dropboxAppSecret, backupConfig.dropboxAccessType)
        if backupConfig.dropboxAccessToken == gEmptyStr or not backupConfig.dropboxAccessToken:
            requestToken = sess.obtain_request_token()
            url = sess.build_authorize_url(requestToken)
            # Make the user sign in and authorize this token
            print("url: %s" % url)
            print("Please visit this website and press the 'Allow' button, then hit 'Enter' here.")
            raw_input()
            accessToken = sess.obtain_access_token(requestToken)
            # encrypt access token
            dropboxAccessTokenAesKey = aes.generateRandomKey(16)
            accessTokenKey = aes.encryptData(dropboxAccessTokenAesKey, accessToken.key)
            accessTokenSecret = aes.encryptData(dropboxAccessTokenAesKey, accessToken.secret)
            backupConfig.configParser.set(
                backupConfig.DropboxSection,
                "access_token",
                "%s:%s:%s" % (accessTokenKey.encode("hex"), accessTokenSecret.encode("hex"), dropboxAccessTokenAesKey.encode("hex")))
            client = client.DropboxClient(sess)
        else:
            # read access token
            if not backupConfig.dropboxAccessToken or backupConfig.dropboxAccessToken == gEmptyStr:
                raise Exception("Cannot read access_token in config file %s" % backupConfig.configPath)
            accessTokenKey, accessTokenSecret, dropboxAccessTokenAesKey = backupConfig.dropboxAccessToken.split(":")
            accessTokenKey = aes.decryptData(binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenKey))
            accessTokenSecret = aes.decryptData(binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenSecret))
            sess.set_token(accessTokenKey, accessTokenSecret)
            # init client
            client = client.DropboxClient(sess)
        # send backup file
        with open(backupArchive) as f:
            print("Upload %s to dropbox..." % (backupArchive))
            response = client.put_file("%s/%s" % (backupConfig.dropboxBackupDir, os.path.basename(allBackupArchive)), f)
Пример #18
0
def genwallet(seed, pw, email):
    encseed = aes.encryptData(pw, seed)
    ethpriv = sha3(seed)
    btcpriv = sha3(seed + '\x01')
    ethaddr = sha3(secure_privtopub(ethpriv)[1:])[12:].encode('hex')
    btcaddr = privtoaddr(btcpriv)
    return {
        "encseed": encseed.encode('hex'),
        "ethaddr": ethaddr,
        "btcaddr": btcaddr,
        "email": email
    }
Пример #19
0
def genwallet(seed, pw, email):
    encseed = aes.encryptData(pw, seed)
    ethpriv = sha3(seed)
    btcpriv = sha3(seed + '\x01')
    ethaddr = sha3(secure_privtopub(ethpriv)[1:])[12:].encode('hex')
    btcaddr = privtoaddr(btcpriv)
    return {
        "encseed": encseed.encode('hex'),
        "ethaddr": ethaddr,
        "btcaddr": btcaddr,
        "email": email
    }
Пример #20
0
def genwallet(seed, pw):
    encseed = aes.encryptData(pw, seed)
    ethpriv = sha3(seed)
    btcpriv = sha3(seed + '\x01')
    ethaddr = sha3(secure_privtopub(ethpriv)[1:])[12:].encode('hex')
    btcaddr = privtoaddr(btcpriv)
    bkp = sha3(seed + '\x02').encode('hex')[:32]
    return {
        "encseed": encseed.encode('hex'),
        "bkp": bkp,
        "ethaddr": ethaddr,
        "btcaddr": btcaddr,
    }
Пример #21
0
def basic_protocol(p, g):
    # A->B            Send "p", "g", "A"
    a, A = keygen(p, g)

    # B->A            Send "B"
    b, B = keygen(p, g)

    # A->B            Send AES-CBC(SHA1(s)[0:16], iv=random(16), msg) + iv
    s_A = pow(B, a, p)
    aeskey_A = derivekey(s_A)    
    msg_A = 'hello world'
    cipher_A = aes.encryptData(aeskey_A, msg_A)
    
    # B->A            Send AES-CBC(SHA1(s)[0:16], iv=random(16), A's msg) + iv
    s_B = pow(A, b, p)
    aeskey_B = derivekey(s_B)
    msg_B = aes.decryptData(aeskey_B, cipher_A)
    cipher_B = aes.encryptData(aeskey_B, msg_B)

    # (A checks B's msg?)
    check_A = aes.decryptData(aeskey_A, cipher_B)
    assert msg_A == check_A and msg_B == msg_A
Пример #22
0
def send(message, contact):
    data = config.my_data.find("data", "all")[0]
    target = config.nodes.find("nodes", {"address":contact})[0]
    address = data['address']
    stamp = time.time()
    config.cache.insert("sent", {"message":message, "contact":contact, "time":stamp})
    config.cache.save()
    public_key = filter(None, re.findall("[0-9]*", target['publickey'])) #Safe way of extracting the public key from a string
    public_key = PublicKey(int(public_key[0]), int(public_key[1])) # Re build public key
    key = uuid.uuid4().hex  # Generate AES key
    k = encrypt(key, public_key) #Encrypt the key with the RSA public key of the target
    k = base64.b64encode(k) #Encode the encrypted data
    message = base64.b64encode(aes.encryptData(key, message)) #Encrypt the message with the AES key and then encode it
    broadcast.send({"cmd":"send_message", "message":message, "contact":contact, "address":address, "key":k, "time":stamp}, False) #Broadcast the message
Пример #23
0
def genwallet(seed,pw,email):
    if not seed:
        seed = random_key().decode('hex') # uses pybitcointools' 3-source random generator
    encseed = aes.encryptData(pbkdf2(pw),seed)
    ethpriv = sha3(seed)
    btcpriv = sha3(seed + '\x01')
    ethaddr = sha3(privtopub(ethpriv)[1:])[12:].encode('hex')
    btcaddr = privtoaddr(btcpriv)
    bkp = sha3(seed + '\x02').encode('hex')
    return {
        "encseed": encseed.encode('hex'),
        "bkp": bkp,
        "ethaddr": ethaddr,
        "btcaddr": btcaddr,
        "email": email
    }
Пример #24
0
 def resend(self, src, dest, node_pub_key):
     aeskey = str(uuid.uuid4().hex)  # Generate new AES Key
     key = encrypt(aeskey, eval(str(node_pub_key)))  # Encrypt AES key with target's RSA Public Key
     key = base64.b64encode(key)  # Base64 encode the key
     # print "Sent this base64 encoded key: " + key
     dest.sendall(key)
     data = src.recv(10)
     while data:
         crypted_data = aes.encryptData(aeskey, data)  # Encrypt Message with AES Key
         crypted_data = base64.b64encode(crypted_data)  # Base64 encode the crypted data
         print "Sent: " + crypted_data
         dest.sendall(crypted_data)
         data = src.recv(10)
     src.close()
     dest.close()
     print ("Client quit normally\n")
Пример #25
0
 def _parse_dropbox(self):
     self.dropboxAccessToken = self.configParser.get(
         self.DropboxSection, "access_token")
     if self.backupWithDropbox != gEmptyStr and self.backupWithDropbox:
         # get dropbox auth info
         self.dropboxUser = self.configParser.get(self.DropboxSection,
                                                  "User")
         if self.dropboxUser:
             self.dropboxUser = self.dropboxUser.strip()
         self.dropboxPassStr = self.configParser.get(
             self.DropboxSection, "Password")
         if self.dropboxPassStr:
             self.dropboxPassStr = self.dropboxPassStr.strip()
         if not self.dropboxUser or gEmptyStr == self.dropboxUser:
             self.dropboxUser = raw_input("Your user name for dropbox: ")
             self.configParser.set(self.DropboxSection, "User",
                                   self.dropboxUser)
             self.dropboxPassStr = ""
         if not self.dropboxPassStr or self.dropboxPassStr == gEmptyStr:
             self.dropboxPassStr = getpass.getpass(
                 "Your password for dropbox user %s: " % (self.dropboxUser))
             self.dropboxPassKey = aes.generateRandomKey(16)
             # set password with aes encryption
             tmpPass = aes.encryptData(dropboxPassKey, dropboxPassStr)
             self.configParser.set(
                 self.DropboxSection, "Password",
                 tmpPass.encode("hex") + gSepChar +
                 self.dropboxPassKey.encode("hex"))
             # reset access token when username or password changes
             self.dropboxAccessToken = gEmptyStr
         else:
             self.dropboxPass, self.dropboxPassKey = self.dropboxPassStr.split(
                 ":")
             self.dropboxPass = aes.decryptData(
                 binascii.unhexlify(self.dropboxPassKey),
                 binascii.unhexlify(self.dropboxPass))
     self.dropboxAppKey = self.configParser.get(self.DropboxSection,
                                                "APP_KEY")
     self.dropboxAppSecret = self.configParser.get(self.DropboxSection,
                                                   "APP_SECRET")
     self.dropboxAccessType = "dropbox"
     self.dropboxBackupDir = self.configParser.get(self.DropboxSection,
                                                   "target_dir")
     if not self.dropboxBackupDir:
         self.dropboxBackupDir = "/"
     else:
         self.dropboxBackupDir = self.dropboxBackupDir.rstrip("/")
Пример #26
0
def genwallet(seed, pw, email):
    if not seed:
        seed = random_key().decode(
            'hex')  # uses pybitcointools' 3-source random generator
    encseed = aes.encryptData(pbkdf2(pw), seed)
    ethpriv = sha3(seed)
    btcpriv = sha3(seed + '\x01')
    ethaddr = sha3(privtopub(ethpriv)[1:])[12:].encode('hex')
    btcaddr = privtoaddr(btcpriv)
    bkp = sha3(seed + '\x02').encode('hex')
    return {
        "encseed": encseed.encode('hex'),
        "bkp": bkp,
        "ethaddr": ethaddr,
        "btcaddr": btcaddr,
        "email": email
    }
Пример #27
0
def encrypt(password, plaintext, chunkit=True, msgdgst='md5'):
    '''
    Encrypt the plaintext using the password using an openssl
    compatible encryption algorithm. It is the same as creating a file
    with plaintext contents and running openssl like this:

    $ cat plaintext
    <plaintext>
    $ openssl enc -e -aes-256-cbc -base64 -salt \\
        -pass pass:<password> -n plaintext

    @param password  The password.
    @param plaintext The plaintext to encrypt.
    @param chunkit   Flag that tells encrypt to split the ciphertext
                     into 64 character (MIME encoded) lines.
                     This does not affect the decrypt operation.
    @param msgdgst   The message digest algorithm.
    '''
    salt = os.urandom(8)
    key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst)
    if key is None:
        return None

    # PKCS#7 padding
    padding_len = 16 - (len(plaintext) % 16)
    padded_plaintext = plaintext + (chr(padding_len) * padding_len)

    # Encrypt
    #cipher = AES.new(key, AES.MODE_CBC, iv)
    #ciphertext = cipher.encrypt(padded_plaintext)
    ciphertext = aes.encryptData(key, padded_plaintext)

    # Make openssl compatible.
    # I first discovered this when I wrote the C++ Cipher class.
    # CITATION: http://projects.joelinoff.com/cipher-1.1/doxydocs/html/
    openssl_ciphertext = 'Salted__' + salt + ciphertext
    b64 = base64.b64encode(openssl_ciphertext)
    if not chunkit:
        return b64

    LINELEN = 64
    chunk = lambda s: '\n'.join(s[i:min(i+LINELEN, len(s))]
                                for i in xrange(0, len(s), LINELEN))
    return chunk(b64)
Пример #28
0
    def _set_db_info(self):
        if not self.dbConf:
            return False

        for dbtype in self.dbType:
            dbConf = self.dbConf.get(dbtype, None)
            if dbConf is None or not dbConf.dbList:
                continue
            # set user and password/key
            if not dbConf.dbUser or dbConf.dbUser == gEmptyStr:
                dbConf.dbUser = raw_input("Your user name for %s: " % dbtype)
                self.configParser.set(dbtype, "User", dbConf.dbUser)
                dbConf.dbPass = ""
            if not dbConf.dbPass or dbConf.dbPass == gEmptyStr:
                dbConf.dbPass = getpass.getpass(
                    "Your password for %s user %s: " % (dbtype, dbConf.dbUser))
                dbConf.dbPassKey = aes.generateRandomKey(16)
                # set password with aes encryption
                tmpPass = aes.encryptData(dbConf.dbPassKey, dbConf.dbPass)
                self.configParser.set(
                    dbtype, "Password",
                    tmpPass.encode("hex") + gSepChar +
                    dbConf.dbPassKey.encode("hex"))
            else:
                dbConf.dbPass, dbConf.dbPassKey = dbConf.dbPass.split(":")
                dbConf.dbPass = aes.decryptData(
                    binascii.unhexlify(dbConf.dbPassKey),
                    binascii.unhexlify(dbConf.dbPass))
            # set dump command
            if dbtype == self.MysqlSection:
                dbPort = "-P %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else ""
                dbConf.dumpCmd = "mysqldump %s -u %s --password=%s -B {0} -r %s/{0}" % \
                    (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir)
            elif dbtype == self.MongoDBSection:
                dbPort = "--port %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else ""
                dbConf.dumpCmd = "mongodump %s -u %s -p %s -d {0} -o %s/mongodb" % \
                    (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir)
            else:
                print("Fatal error: database type %s is not supported" %
                      dbtype)
                sys.exit(1)

        return True
Пример #29
0
def encrypt(password, plaintext, chunkit=True, msgdgst="md5"):
    """
    Encrypt the plaintext using the password using an openssl
    compatible encryption algorithm. It is the same as creating a file
    with plaintext contents and running openssl like this:

    $ cat plaintext
    <plaintext>
    $ openssl enc -e -aes-256-cbc -base64 -salt \\
        -pass pass:<password> -n plaintext

    @param password  The password.
    @param plaintext The plaintext to encrypt.
    @param chunkit   Flag that tells encrypt to split the ciphertext
                     into 64 character (MIME encoded) lines.
                     This does not affect the decrypt operation.
    @param msgdgst   The message digest algorithm.
    """
    salt = os.urandom(8)
    key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst)
    if key is None:
        return None

    # PKCS#7 padding
    padding_len = 16 - (len(plaintext) % 16)
    padded_plaintext = plaintext + (chr(padding_len) * padding_len)

    # Encrypt
    # cipher = AES.new(key, AES.MODE_CBC, iv)
    # ciphertext = cipher.encrypt(padded_plaintext)
    ciphertext = aes.encryptData(key, padded_plaintext)

    # Make openssl compatible.
    # I first discovered this when I wrote the C++ Cipher class.
    # CITATION: http://projects.joelinoff.com/cipher-1.1/doxydocs/html/
    openssl_ciphertext = "Salted__" + salt + ciphertext
    b64 = base64.b64encode(openssl_ciphertext)
    if not chunkit:
        return b64

    LINELEN = 64
    chunk = lambda s: "\n".join(s[i : min(i + LINELEN, len(s))] for i in xrange(0, len(s), LINELEN))
    return chunk(b64)
Пример #30
0
def send_msg(msg, title, to, addr):
    # Copied and pasted from read.py
    my_key = db.data.find("data", "all")[0]["privatekey"]
    if my_key.startswith("PrivateKey(") and my_key.endswith(")"):
        my_key = eval(my_key)

    try:
        data = db.nodes.find("nodes", {"addr":to})[0]
    except:
        return "Address doesn't exist"
    if data['publickey'].startswith("PublicKey(") and data['publickey'].endswith(")"):
       # msg = encrypt(msg, eval(data['publickey'])) <--- Old encryption code
	aeskey = str(uuid.uuid4().hex) # Generate new AES Key
	key = encrypt(aeskey, eval(data['publickey'])) # Encrypt AES key with target's RSA Public Key
	key = base64.b64encode(key) # Base64 encode the key
	msg = aes.encryptData(aeskey,msg) # Encrypt Message with AES Key
        msg = base64.b64encode(msg) # Base64 encode the message
	as_num, as_nonce = antispam.find_antispam(to,addr,msg,antispam.get_required_difficulty(msg)) # Generate the AntiSpam
        signature = base64.b64encode(sign(msg + to,my_key,"SHA-1")) # Sign the message
    else:
        return "Invalid public key for", addr
    id = ""
    while True:
        id = uuid.uuid4().hex
        if db.messages.find("messages", {"id":id}):
            continue
        else:
            break
    print "Sending message ID " + id + " with key " + key + " and signature " + signature
    nodes = db.nodes.find("nodes", "all")
    t = time.localtime()
    time_ = "{0}/{1}/{2} {3}:{4}:{5}".format(t[1], t[2], t[0], t[3], t[4], t[5])
    for x in nodes:
        s = ssl.socket()
        try:
            s.settimeout(1)
            s.connect((x['ip'], x['port']))
            s.send(json.dumps({"cmd":"message", "time":time_ ,"id":id, "message":msg, "title":title, "to":to, "from":addr,"num":as_num,"nonce":as_nonce,"key":key,"signature":signature}))
            s.close()
        except Exception, error:
            db.unsent.insert("unsent", {"to":[x['ip'], x['port']], "message":{"cmd":"message", "time":time_, "id":id, "message":msg, "title":title, "to":to, "from":addr,"num":as_num,"nonce":as_nonce,"key":key,"signature":signature}})
Пример #31
0
    def encrypt_message(self, message, pubkey):

        pk = ser_to_point(pubkey)
        if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()):
            raise Exception('invalid pubkey')

        ephemeral_exponent = number_to_string(ecdsa.util.randrange(pow(2,256)), generator_secp256k1.order())
        ephemeral = EC_KEY(ephemeral_exponent)

        ecdh_key = (pk * ephemeral.privkey.secret_multiplier).x()
        ecdh_key = ('%064x' % ecdh_key).decode('hex')
        key = hashlib.sha512(ecdh_key).digest()
        key_e, key_m = key[:32], key[32:]

        iv_ciphertext = aes.encryptData(key_e, message)

        ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex')
        encrypted = 'BIE1' + ephemeral_pubkey + iv_ciphertext
        mac = hmac.new(key_m, encrypted, hashlib.sha256).digest()

        return base64.b64encode(encrypted + mac)
Пример #32
0
    def encrypt_message(self, message, pubkey):

        pk = ser_to_point(pubkey)
        if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()):
            raise Exception('invalid pubkey')

        ephemeral_exponent = number_to_string(
            ecdsa.util.randrange(pow(2, 256)), generator_secp256k1.order())
        ephemeral = EC_KEY(ephemeral_exponent)

        ecdh_key = (pk * ephemeral.privkey.secret_multiplier).x()
        ecdh_key = ('%064x' % ecdh_key).decode('hex')
        key = hashlib.sha512(ecdh_key).digest()
        key_e, key_m = key[:32], key[32:]

        iv_ciphertext = aes.encryptData(key_e, message)

        ephemeral_pubkey = ephemeral.get_public_key(
            compressed=True).decode('hex')
        encrypted = 'BIE1' + ephemeral_pubkey + iv_ciphertext
        mac = hmac.new(key_m, encrypted, hashlib.sha256).digest()

        return base64.b64encode(encrypted + mac)
Пример #33
0
    def _set_db_info(self):
        if not self.dbConf:
            return False

        for dbtype in self.dbType:
            dbConf = self.dbConf.get(dbtype, None)
            if dbConf is None or not dbConf.dbList:
                continue
            # set user and password/key
            if not dbConf.dbUser or dbConf.dbUser == gEmptyStr:
                dbConf.dbUser = raw_input("Your user name for %s: " % dbtype)
                self.configParser.set(dbtype, "User", dbConf.dbUser)
                dbConf.dbPass = ""
            if not dbConf.dbPass or dbConf.dbPass == gEmptyStr:
                dbConf.dbPass = getpass.getpass("Your password for %s user %s: " % (dbtype, dbConf.dbUser))
                dbConf.dbPassKey = aes.generateRandomKey(16)
                # set password with aes encryption
                tmpPass = aes.encryptData(dbConf.dbPassKey, dbConf.dbPass)
                self.configParser.set(dbtype, "Password", tmpPass.encode("hex") + gSepChar + dbConf.dbPassKey.encode("hex"))
            else:
                dbConf.dbPass, dbConf.dbPassKey = dbConf.dbPass.split(":")
                dbConf.dbPass = aes.decryptData(binascii.unhexlify(dbConf.dbPassKey), binascii.unhexlify(dbConf.dbPass))
            # set dump command
            if dbtype == self.MysqlSection:
                dbPort = "-P %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else ""
                dbConf.dumpCmd = "mysqldump %s -u %s --password=%s -B {0} -r %s/{0}" % \
                    (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir)
            elif dbtype == self.MongoDBSection:
                dbPort = "--port %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else ""
                dbConf.dumpCmd = "mongodump %s -u %s -p %s -d {0} -o %s/mongodb" % \
                    (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir)
            else:
                print("Fatal error: database type %s is not supported" % dbtype)
                sys.exit(1)

        return True
Пример #34
0
def finalize(wallet,unspent,pw):
    seed = getseed(wallet["encseed"],pw,wallet["ethaddr"]) 
    balance = sum([o["value"] for o in unspent])
    if balance == 0:
        raise Exception("No funds in address")
    if balance < 1000000:
        raise Exception("Insufficient funds. Need at least 0.01 BTC")
    ephem = random_key().decode('hex')
    shared = multiply(our_pubkey,ephem)
    data = aes.encryptData(shared[:16],wallet["email"]) + compress(privtopub(ephem))
    data = chr(len(data)) + data
    outs = [
        exodus+':'+str(balance - 70000),
        hex_to_b58check(wallet["ethaddr"])+':10000'
    ]
    while len(data) > 0:
        d = data[:20] + '\x00' * max(0,20 - len(data))
        outs.append(bin_to_b58check(d)+':10000')
        data = data[20:]
    tx = mktx(unspent,outs)
    btcpriv = sha3(seed+'\x01')
    for i in range(len(unspent)):
        tx = sign(tx,i,btcpriv)
    return tx
Пример #35
0
def aes_cbcmac(key, msg, iv = '\0' * 16):
    return aes.encryptData(key, msg, iv = iv)[-16:]
Пример #36
0
def encrypt_privkey(privkey, pw):
    bin_pwhash = bin_hash_password(pw)
    bin_encr_privkey = aes.encryptData(bin_pwhash, privkey)
    encr_privkey = bin_encr_privkey.encode('hex')
    
    return encr_privkey
Пример #37
0
def encrypt_privkey(privkey, pw):
    bin_pwhash = bin_hash_password(pw)
    bin_encr_privkey = aes.encryptData(bin_pwhash, privkey)
    encr_privkey = bin_encr_privkey.encode('hex')

    return encr_privkey
Пример #38
0
def aes_cbcmac(key, msg):
    cipher = aes.encryptData(key, msg, iv='\0' * 16)
    return cipher[-16:]
Пример #39
0
def aes_cbcmac_nopad(key, msg):
    cipher = aes.encryptData(key, msg, iv='\0' * 16, pad=False)
    return cipher[-16:]
Пример #40
0
def aes_cbcmac(key, msg):
    cipher = aes.encryptData(key, msg, iv = '\0' * 16)
    return cipher[-16:]
Пример #41
0
def encrypted(pwd, s):
    return str_to_base58(aes.encryptData(dhash(pwd), s))
Пример #42
0
def encryptAES(key, data, mode=2):
    """encrypt data with aes key"""
    return aes.encryptData(key, data, mode)
Пример #43
0
import aes
import sqlite3
import serializeBTC as ser
import Crypto.Cipher.AES as AES
import Crypto.Hash.SHA256 as SHA256
import scrypt
from itertools import izip
from array import array
from bitcoin.bip38 import Bip38
from bitcoin.key import CKey
from bitcoin.base58 import CBase58Data, CBitcoinAddress

Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest()

# AES encryption
EncodeAES = lambda secret, s: b58encode(aes.encryptData(secret,s))
DecodeAES = lambda secret, e: aes.decryptData(secret, b58decode(e))

# Electrum uses base64, which is fine when it's stored in the computer, but base58 was created for readibiity by humans
# AES encryption
#EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
#DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))


#BIO0038
def encryptBIP0038(pubkey, privkey, secret):
	k = CKey()
	#decode the wallet import format by base58 decoding then dropping the last 4 bytes and the first byte
	decoded = b58decode(privkey)
	decoded = decoded[:-4]
	decoded = decoded[1:]
Пример #44
0
def aes_cbcmac_nopad(key, msg):
    cipher = aes.encryptData(key, msg, iv = '\0' * 16, pad = False)
    return cipher[-16:]
Пример #45
0
def encrypted(pwd, s):
    return str_to_base58(aes.encryptData(dhash(pwd), s))
Пример #46
0
def send_msg(msg, title, to, addr):
    try:
        data = db.nodes.find("nodes", {"addr": to})[0]
    except:
        return "Address doesn't exist"
    if data['publickey'].startswith(
            "PublicKey(") and data['publickey'].endswith(")"):
        # msg = encrypt(msg, eval(data['publickey'])) <--- Old encryption code
        aeskey = str(uuid.uuid4().hex)  # Generate new AES Key
        key = encrypt(aeskey, eval(
            data['publickey']))  # Encrypt AES key with target's RSA Public Key
        key = base64.b64encode(key)  # Base64 encode the key
        msg = aes.encryptData(aeskey, msg)  # Encrypt Message with AES Key
        msg = base64.b64encode(msg)  # Base64 encode the message
        as_num, as_nonce = antispam.find_antispam(
            to, addr, msg, antispam.get_required_difficulty(msg))
    else:
        return "Invalid public key for", addr
    id = ""
    while True:
        id = uuid.uuid4().hex
        if db.messages.find("messages", {"id": id}):
            continue
        else:
            break
    print "Sending message ID " + id + " with key " + key
    nodes = db.nodes.find("nodes", "all")
    for x in nodes:
        s = ssl.socket()
        try:
            s.settimeout(1)
            s.connect((x['ip'], x['port']))
            s.send(
                json.dumps({
                    "cmd": "message",
                    "id": id,
                    "message": msg,
                    "title": title,
                    "to": to,
                    "from": addr,
                    "num": as_num,
                    "nonce": as_nonce,
                    "key": key
                }))
            s.close()
        except Exception, error:
            db.unsent.insert(
                "unsent", {
                    "to": [x['ip'], x['port']],
                    "message": {
                        "cmd": "message",
                        "id": id,
                        "message": msg,
                        "title": title,
                        "to": to,
                        "from": addr,
                        "num": as_num,
                        "nonce": as_nonce,
                        "key": key
                    }
                })
Пример #47
0
from NTRU.main import *
import base64
import aes
n = NTRU()
pub, params = n.generateNTRUKeys()
msg = "Hello world! I am intangere!"
aeskey = str(uuid.uuid4().hex)
aesMsg = base64.b64encode(aes.encryptData(aeskey, msg))
aesParts = n.splitNthChar(7, aesMsg)
print params
encryptedParts = n.encryptParts([71,29,491531], pub, aesParts)
decryptedParts = n.decryptParts(params, encryptedParts)
print "Pubkey: %s" % pub
print "Params: %s" % params
print "Message: %s" % msg
print "Aes Message: %s" % aesMsg
print "Ntru Parts: %s" % encryptedParts
print "Decrypted Message: %s" % decryptedParts
print "Decrypted Aes Message: %s" % aes.decryptData(aeskey, base64.b64decode(decryptedParts))
Пример #48
0
        seed = btc.sha256(os.urandom(64))[:32]
        words = old_mnemonic.mn_encode(seed)
        print 'Write down this wallet recovery seed\n\n' + ' '.join(
            words) + '\n'
    elif method == 'recover':
        words = raw_input('Input 12 word recovery seed: ')
        words = words.split(' ')
        seed = old_mnemonic.mn_decode(words)
        print seed
    password = getpass.getpass('Enter wallet encryption passphrase: ')
    password2 = getpass.getpass('Reenter wallet encryption passphrase: ')
    if password != password2:
        print 'ERROR. Passwords did not match'
        sys.exit(0)
    password_key = btc.bin_dbl_sha256(password)
    encrypted_seed = aes.encryptData(password_key, seed.decode('hex'))
    timestamp = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
    walletfile = json.dumps({
        'creator': 'joinmarket project',
        'creation_time': timestamp,
        'encrypted_seed': encrypted_seed.encode('hex'),
        'network': common.get_network()
    })
    walletname = raw_input('Input wallet file name (default: wallet.json): ')
    if len(walletname) == 0:
        walletname = 'wallet.json'
    fd = open(os.path.join('wallets', walletname), 'w')
    fd.write(walletfile)
    fd.close()
    print 'saved to ' + walletname
elif method == 'showseed':
Пример #49
0
def aes_cbcmac(key, msg):
    return aes.encryptData(key, msg, iv = '\0' * 16)[-16:]
Пример #50
0
 def encode(self, message):
     encrypted = aes.encryptData(self.encode_password, unicode(message))
     encoded_message = base64.b64encode(encrypted)
     return encoded_message
Пример #51
0
 def encrypt_file(self, key, in_filename, out_filename):
     with open(in_filename, 'rb') as infile:
         with open(out_filename, 'wb') as outfile:
             outfile.write(aes.encryptData(key, infile.read()))
Пример #52
0
from util import print_error, InvalidPassword

import ecdsa
import aes

################################## transactions

DUST_THRESHOLD = 0
DUST_SOFT_LIMIT = 100000
MIN_RELAY_TX_FEE = 100000
RECOMMENDED_FEE = 100000
COINBASE_MATURITY = 100
COIN = 100000000

# AES encryption
EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))

def strip_PKCS7_padding(s):
    """return s stripped of PKCS7 padding"""
    if len(s)%16 or not s:
        raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
    numpads = ord(s[-1])
    if numpads > 16:
        raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
    if s[-numpads:] != numpads*chr(numpads):
        raise ValueError("Invalid PKCS7 padding")
    return s[:-numpads]

# backport padding fix to AES module
aes.strip_PKCS7_padding = strip_PKCS7_padding
Пример #53
0
public_B = get_key(G, b, P)

fake_A = P
fake_B = P

private_A = get_key(fake_B, a, P)
private_B = get_key(fake_A, b, P)


def sha(s):
    return sha1(hex(int(s))).digest()[0:16]


AES_A = sha(private_A)
msg_A = "12345"
cipher_A = aes.encryptData(AES_A, msg_A)


AES_M = sha(0)
msg_AM = aes.decryptData(AES_M, cipher_A)
assert msg_AM == msg_A


AES_B = sha(private_B)
msg_B = aes.decryptData(AES_B, cipher_A)
cipher_B = aes.encryptData(AES_B, msg_B)


msg_BM = aes.decryptData(AES_M, cipher_B)

assert msg_BM == msg_A
Пример #54
0
    def encode(self, message):
        encrypted = aes.encryptData(self.encode_password, unicode(message))
        encoded_message = base64.b64encode(encrypted)

        return encoded_message
Пример #55
0
################################## transactions

FEE_STEP = 10000
RECOMMENDED_FEE = 50000
COINBASE_MATURITY = 100
COIN = 100000000

# supported types of transction outputs
TYPE_ADDRESS = 0
TYPE_PUBKEY  = 1
TYPE_SCRIPT  = 2


# AES encryption
EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))

def strip_PKCS7_padding(s):
    """return s stripped of PKCS7 padding"""
    if len(s)%16 or not s:
        raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
    numpads = ord(s[-1])
    if numpads > 16:
        raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
    if s[-numpads:] != numpads*chr(numpads):
        raise ValueError("Invalid PKCS7 padding")
    return s[:-numpads]

# backport padding fix to AES module
aes.strip_PKCS7_padding = strip_PKCS7_padding
Пример #56
-1
def mitm_protocol():
    # A->M            Send "p", "g", "A"
    a, A = keygen()
    
    # M->B            Send "p", "g", "p"
    B_idea_of_A = p
    
    # B->M            Send "B"
    b, B = keygen()
    
    # M->A            Send "p"
    A_idea_of_B = p
    
    # A->M            Send AES-CBC(SHA1(s)[0:16], iv=random(16), msg) + iv
    s_A = pow(A_idea_of_B, a, p)
    aeskey_A = derivekey(s_A)
    msg_A = 'hello world'
    cipher_A = aes.encryptData(aeskey_A, msg_A)
    
    # M->B            Relay that to B
    # (check we can decrypt)
    aeskey_M = derivekey(0)
    msg_AM = aes.decryptData(aeskey_M, cipher_A)
    assert msg_AM == msg_A
    
    # B->M            Send AES-CBC(SHA1(s)[0:16], iv=random(16), A's msg) + iv
    s_B = pow(B_idea_of_A, b, p)
    aeskey_B = derivekey(s_B)
    msg_B = aes.decryptData(aeskey_B, cipher_A)
    cipher_B = aes.encryptData(aeskey_B, msg_B)
    
    # M->A            Relay that to A
    msg_BM = aes.decryptData(aeskey_M, cipher_B)
    assert msg_BM == msg_A
    assert aeskey_M == aeskey_A