Categories
Python Answers

How to encrypt and decrypt using PyCrypto AES-256?

Sometimes, we want to encrypt and decrypt using PyCrypto AES-256.

In this article, we’ll look at how to encrypt and decrypt using PyCrypto AES-256.

How to encrypt and decrypt using PyCrypto AES-256?

To encrypt and decrypt using PyCrypto AES-256, we can use the PyCryptodome package.

To install it, we run:

pip install pycryptodome

Then we can use it by writing:

import base64
import hashlib
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

__key__ = hashlib.sha256(b'16-character key').digest()


def encrypt(raw):
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key=__key__, mode=AES.MODE_CFB, iv=iv)
    return base64.b64encode(iv + cipher.encrypt(raw))


def decrypt(enc):
    unpad = lambda s: s[:-ord(s[-1:])]

    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(__key__, AES.MODE_CFB, iv)
    return unpad(
        base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))


encrypted = encrypt('foo')
decrypted = decrypt(encrypted)
print(encrypted)
print(decrypted)

We create a key with the haslib.sha256 method with a binary string.

We call digest to return a hash of the key.

Then we call encrypt with the raw string to encrypt.

We encrypt by padding the string with the pad function.

Then we encode the string to base64 woth b64encode and encode.

Next, we call get_random_bytes to get some random bytes that we use to create the cipher.

Finally, we return the encrypted string which we generate with b64encode, iv and cipher.encrypt.

Then we define the decrypt function that has the unpad function to unpad the enc encrypted string.

Next, we call b64decode with enc to decode the encrypted string.

Then we get iv from the enc string by slicing it from index 0 to AES.block_size exclusively.

Then we call AES.new with the secret __key__, AES.MODE_CFB, and iv to get the cipher.

And we call unpad with the decoded cipher base64 cipher string to decrypt the string.

A regular string is returned since we called decode on the decrypted string.

Therefore, encrypted is b'zEMqurGW5NgwRwSAJ0lyejwF3Md02LtlC7oxP/SVJJVI/VLwQqpvvw=='

And decrypted is 'foo'.

Conclusion

To encrypt and decrypt using PyCrypto AES-256, we can use the PyCryptodome package.

Categories
Python Answers

How to add an extra column to a NumPy array with Python?

Sometimes, we want to add an extra column to a NumPy array with Python.

In this article, we’ll look at how to add an extra column to a NumPy array with Python.

How to add an extra column to a NumPy array with Python?

To add an extra column to a NumPy array with Python, we can use the append method.

For instance, we write:

import numpy as np
a = np.array([[1,2,3],[2,3,4]])
z = np.zeros((2,1), dtype=np.int64)
b = np.append(a, z, axis=1)
print(b)

We create the array a with np.array.

Then we call np.zeroes with the dimensions of the array passed in as a tuple and the data type set as the value of dtype.

Then we call append with a and z to append z to a.

It returns a new array and we assign that to b.

Therefore, b is:

[[1 2 3 0]
 [2 3 4 0]]

Conclusion

To add an extra column to a NumPy array with Python, we can use the append method.

Categories
Python Answers

How to remove the ANSI escape sequences from a string in Python?

Sometimes, we want to remove the ANSI escape sequences from a string in Python.

In this article, we’ll look at how to remove the ANSI escape sequences from a string in Python.

How to remove the ANSI escape sequences from a string in Python?

To remove the ANSI escape sequences from a string in Python, we can use the regex’s sub method.

For instance, we write:

import re

ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
sometext = 'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m'
s = ansi_escape.sub('', sometext)
print(s)

We call re.compile with a regex string that has the ANSI escape characters.

Then we have the sometext string that has some ANSI escape characters we want to remove.

To do that, we call ansi_escape.sub with an empty string and sometext to return a new string without the escape characters.

Therefore, s is:

ls
examplefile.zip

Conclusion

To remove the ANSI escape sequences from a string in Python, we can use the regex’s sub method.

Categories
Python Answers

How to ignore the first line of data when processing CSV data with Python?

Sometimes, we want to ignore the first line of data when processing CSV data with Python.

In this article, we’ll look at how to ignore the first line of data when processing CSV data with Python.

How to ignore the first line of data when processing CSV data with Python?

To ignore the first line of data when processing CSV data with Python, we can call next to skip to the next row.

For instance, if we have:

test.csv

col1,col2
1,2
3,4
5,6

Then we write:

import csv
with open('test.csv') as f:
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
        print(row)

to open the test.csv with open.

Then we call csv.reader with f to read the file.

Next, we skip the first row by calling next with f_csv.

The first row’s data is returned with next and assigned to headers.

And finally, we loop through the rest of the rows with a for loop and print each row.

Therefore, we see:

['1', '2']
['3', '4']
['5', '6']

printed.

Conclusion

To ignore the first line of data when processing CSV data with Python, we can call next to skip to the next row.

Categories
Python Answers

How to get number closest to a given value from a list of integers with Python?

Sometimes, we want to get number closest to a given value from a list of integers with Python.

In this article, we’ll look at how to get number closest to a given value from a list of integers with Python.

How to get number closest to a given value from a list of integers with Python?

To get number closest to a given value from a list of integers with Python, we can use the min function with the key parameter set to a function that returns the absolute difference between the value and the number in the list.

For instance, we write:

my_num = 100
l = [29, 58, 129, 487, 41]
closest = min(l, key=lambda x: abs(x - my_num))
print(closest)

We have my_num which is the number we want to get the closest value to from the list l.

To do that, we call min with l and key set to lambda x: abs(x - my_num)).

lambda x: abs(x - my_num)) returns the absolute difference between x which is an entry in l and my_num.

And then we assign the returned number to closest.

Therefore, closest is 129.

Conclusion

To get number closest to a given value from a list of integers with Python, we can use the min function with the key parameter set to a function that returns the absolute difference between the value and the number in the list.