RSA Encryption

woE7ewVfwoAzbwXCgC5iMyRvBTvCgGBiOy4=
public key: e=5, n=133
import random
import base64

'''
Euclid's algorithm to determine the greatest common divisor
'''
def gcd(a,b):
    while b != 0:
        c = a % b
        a = b
        b = c
    return a

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    g, y, x = egcd(b%a,a)
    return (g, x - (b//a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('No modular inverse')
    return x%m

def encrypt(plaintext,keypair):
    e,n = keypair

    # Encrypt the plaintext
    cipher = ''.join([chr(pow(ord(char),e,n)) for char in plaintext])
    # Encode the ciphertext so it's more readable/sharable
    encoded = base64.b64encode(cipher.encode('utf-8'))
    return str(encoded,'utf-8')

def decrypt(ciphertext,keypair):
    d,n = keypair

    # Decode the text to the original format
    decoded = base64.b64decode(ciphertext).decode('utf-8')
    # Decrypt it
    plain = (str(chr(pow(ord(char),d,n))) for char in decoded)
    return ''.join(plain)

def generate_keypair(p,q,e=None):
    n = p * q

    #Phi is the totient of n
    phi = (p-1)*(q-1)

    #Choose an integer e such that e and phi(n) are coprime
    if e is None:
        e = random.randrange(1, phi)

    #Use Euclid's Algorithm to verify that e and phi(n) are comprime
    g = gcd(e, phi)
    while g != 1:
        e = random.randrange(1, phi)
        g = gcd(e, phi)

    #Now find the multiplicative inverse of e and phi to generate the private key
    d = modinv(e, phi)

    return ((e,n),(d,n))

#Only run this part if we're not running as an imported module
if __name__ == '__main__':
    p = int(input("Enter prime number p: "))
    q = int(input("Enter prime number q: "))

    public, private = generate_keypair(p,q)

    print("Your public key is the number pair of (e=" +  str(public[0]) + ", n=" + str(public[1]) +").\n")
    print("Your private key is the number pair of (d=" +  str(private[0]) + ", n=" + str(private[1]) +").\n")

    s = input("Enter your message: ")
    encrypted = encrypt(s,public)

    print("Encrypted message: " + encrypted)
    decrypted = decrypt(encrypted,private)
    print("Decrypt: " + decrypted)  

BMP-280 with Raspberry Pi and Python Wiring/Code

Adafruit Source

Python Computer Wiring

Since there’s dozens of Linux computers/boards you can use we will show wiring for Raspberry Pi. For other platforms, please visit the guide for CircuitPython on Linux to see whether your platform is supported.

Here’s the Raspberry Pi wired with I2C:

  • adafruit_products_raspi_bmp280_i2c_bb.png
  • Pi 3V3 to sensor VIN
  • Pi GND to sensor GND
  • Pi SCL to sensor SCK
  • Pi SDA to sensor SDI

And an example on the Raspberry Pi 3 Model B wired with SPI:

  • adafruit_products_raspi_bme280_spi_bb.png
  • Pi 3V3 to sensor VIN
  • Pi GND to sensor GND
  • Pi MOSI to sensor SDI
  • Pi MISO to sensor SDO
  • Pi SCLK to sensor SCK
  • Pi #5 to sensor CS (or use any other free GPIO pin)

CircuitPython Installation of BMP280 Library

You’ll need to install the Adafruit CircuitPython BMP280 library on your CircuitPython board.

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you’ll need to install the necessary libraries to use the hardware–carefully follow the steps to find and install these libraries from Adafruit’s CircuitPython library bundle.  Our CircuitPython starter guide has a great page on how to install the library bundle.

For non-express boards like the Trinket M0 or Gemma M0, you’ll need to manually install the necessary libraries from the bundle:

  • adafruit_bmp280.mpy
  • adafruit_bus_device

Before continuing make sure your board’s lib folder or root filesystem has the adafruit_bmp280.mpy, and adafruit_bus_device files and folders copied over.

Next connect to the board’s serial REPL so you are at the CircuitPython >>> prompt.

Python Installation of BMP280 Library

You’ll need to install the Adafruit_Blinka library that provides the CircuitPython support in Python. This may also require enabling I2C on your platform and verifying you are running Python 3. Since each platform is a little different, and Linux changes often, please visit the CircuitPython on Linux guide to get your computer ready!

Once that’s done, from your command line run the following command:

  • sudo pip3 install adafruit-circuitpython-bmp280

If your default Python is version 3 you may need to run ‘pip’ instead. Just make sure you aren’t trying to use CircuitPython on Python 2.x, it isn’t supported!

CircuitPython & Python Usage

To demonstrate the usage of the sensor we’ll initialize it and read the temperature, humidity, and more from the board’s Python REPL.

If you’re using an I2C connection run the following code to import the necessary modules and initialize the I2C connection with the sensor:

 Download: file

  1. import board
  2. import busio
  3. import adafruit_bmp280
  4. i2c = busio.I2C(board.SCL, board.SDA)
  5. sensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)

Or if you’re using a SPI connection run this code instead to setup the SPI connection and sensor:

 Download: file

  1. import board
  2. import busio
  3. import digitalio
  4. import adafruit_bmp280
  5. spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
  6. cs = digitalio.DigitalInOut(board.D5)
  7. sensor = adafruit_bmp280.Adafruit_BMP280_SPI(spi, cs)

Now you’re ready to read values from the sensor using any of these properties:

  • temperature – The sensor temperature in degrees Celsius.
  • pressure – The pressure in hPa.
  • altitude – The altitude in meters.

For example to print temperature and pressure:

 Download: file

  1. print(‘Temperature: {} degrees C’.format(sensor.temperature))
  2. print(‘Pressure: {}hPa’.format(sensor.pressure))
adafruit_products_Screen_Shot_2017-11-10_at_3.33.47_PM.png

For altitude you’ll want to set the pressure at sea level for your location to get the most accurate measure (remember these sensors can only infer altitude based on pressure and need a set calibration point).  Look at your local weather report for a pressure at sea level reading and set the seaLevelhPA property:

 Download: file

  1. sensor.sea_level_pressure = 1013.25

Then read the altitude property for a more accurate altitude reading (but remember this altitude will fluctuate based on atmospheric pressure changes!):

 Download: file

  1. print(‘Altitude: {} meters’.format(sensor.altitude))
adafruit_products_alti.png

That’s all there is to using the BMP280 sensor with CircuitPython!

Here’s a starting example that will print out the temperature, pressure and altitude every 2 seconds:

  1. import time
  2.  
  3. import board
  4. # import digitalio # For use with SPI
  5. import busio
  6.  
  7. import adafruit_bmp280
  8.  
  9. # Create library object using our Bus I2C port
  10. i2c = busio.I2C(board.SCL, board.SDA)
  11. bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)
  12.  
  13. # OR create library object using our Bus SPI port
  14. #spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
  15. #bmp_cs = digitalio.DigitalInOut(board.D10)
  16. #bmp280 = adafruit_bmp280.Adafruit_BMP280_SPI(spi, bmp_cs)
  17.  
  18. # change this to match the location’s pressure (hPa) at sea level
  19. bmp280.sea_level_pressure = 1013.25
  20.  
  21. while True:
  22. print(“\nTemperature: %0.1f C” % bmp280.temperature)
  23. print(“Pressure: %0.1f hPa” % bmp280.pressure)
  24. print(“Altitude = %0.2f meters” % bmp280.altitude)
  25. time.sleep(2)

Chatroom Source

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0',25565))
s.listen(10)

while True:
    print('waiting for new connection')
    conn,addr = s.accept()
    print('New connection: ' + str(addr))

    motd = "Welcome to PolyChat!"
    conn.sendto(bytes(motd,'utf-8'), addr)

    char = ''
    message = ''
    while char != None and char != 'q':
        char,temp = conn.recvfrom(1024)
        char = char.decode('utf-8')
        message += char
        print(message)
        
    conn.close()



Telnet Demo

Enabling Telnet in Windows 10

telnet YOU WILL GET THE SERVER IN CLASS
EHLO totally.legit.server.com
MAIL FROM:<NAME@AURLIWILLGIVEYOU.com>
RCPT TO: <ONEOFOUREMAILS@gmail.com>
DATA
From: Da Boss <NAME@AURLIWILLGIVEYOU.com>
To: The Dude <ONEOFOUREMAILS@gmail.com>
Subject: Totally legit offer for The Dude
Hello Mr The Dude,
I would like to give you lots of free money. Please click this not
at all suspicious link to claim it:
Best,
Da Boss
Totally Legitimate Company, Inc.
.
QUIT

Platformer Python Code


import turtle, random,time
map = input('Select a map from 1-8 or press 9 for random map')
max = 8
map = int(map)
if map == max:
  map = random.randint(1,max-1)
if map == 1:
  mapName = "v"
if map == 2:
  mapName = "d"
if map == 3:
  mapName = "m"
if map == 4:
  mapName = "a"
if map == 5:
  mapName = "j"
if map == 6:
  mapName = "e (1)"
if map == 7:
  mapName = "t"
if map == 8:
  mapName = "l"

charlist = ['rainbowbob','Kataniguana','yurp','REEE','Zhane','america','lightning','Goku','Symmetra','Dva','Junkrat2','Mercy','soldier']
print(charlist)
char1 = int(input('Player 1 Choose a character from the list.'))
char2 = int(input('Player 2 Choose a character from the list.'))
char1 = charlist[char1-1]
char2 = charlist[char2-1]

you = turtle.Turtle()
you.penup()
them = turtle.Turtle()
them.penup()
ball = turtle.Turtle()
screen = turtle.Screen()
screen.setup(400, 400)
direction = "up"
screen.bgpic(mapName+".png")
screen.addshape(char1+".png")
you.shape(char1+".png")
screen.addshape(char2+".png")
them.shape(char2+".png")
move_speed = 10


##MOVEMENT CODE FOR SPRITE 1 (YOU)
def up():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()+move_speed)
  if you.ycor()> 200:
    you.sety(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def down():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()-move_speed)
  if you.ycor()< -200:
    you.sety(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def left():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()-move_speed)
  if you.xcor()< -200:
    you.setx(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def right():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()+move_speed)
  if you.xcor()> 200:
    you.setx(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def jump():
  up()
  up()
  up()
  time.sleep(0.1)
  down()
  down()
  down()
  

##MOVEMENT CODE FOR SPRITE 2 (THEM)
def up2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()+move_speed)
  if them.ycor()> 200:
    them.sety(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def down2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()-move_speed)
  if them.ycor()< -200:
    them.sety(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def left2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()-move_speed)
  if them.xcor()< -200:
    them.setx(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def right2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()+move_speed)
  if them.xcor()> 200:
    them.setx(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def jump2():
  up2()
  up2()
  up2()
  time.sleep(0.1)
  down2()
  down2()
  down2()
  
  
  
def findbox(xold, yold):
  if map == 1:
    coords = [
    [30,90,90,180],
    [10,120,30,70],
    [160,200,-10,70],
    [-160,-20,20,70],
    [-200,-180,20,80],
    [-80,-10,100,180],
    [-170,-120,100,200],
    [-190,-100,-80,-30],
    [-40,10,-90,-40]]
  if map == 7:
     coords = [
    [10,180,-110,-70],
    [10,180,-160,-120],
    [10,180,-180,-160],
    [-80,0,-180,-60],
    [-190,-90,-170,-60],
    [120,200,70,200],
    [20,70,80,190],
    [-160,-20,120,190],
    [-170,-120,70,100],
    [-120,-80,70,100],
    [-70,-30,70,100]]


  sprites = [you, them]
  for i in sprites:
    for j in coords:
      if i.xcor() > j[0] and i.xcor() < j[1]: 
        if i.ycor() > j[2] and i.ycor() < j[3]:
          print('you are in the box')
          i.setx(xold)
          i.sety(yold)
   
def fly(ball):
  global direction
  ball.hideturtle()
  ball.setx(you.xcor())
  ball.sety(you.ycor())
  ball.pendown()
  if direction == "up":
    ball.sety(200)
  if direction == "down":
    ball.sety(-200)
  if direction == "left":
    ball.setx(-200)
  if direction == "right":
    ball.setx(200)
  ball.penup()
  ball.showturtle()

you.penup()
you.speed(0)
you.home()
you.left(90)

them.penup()
them.speed(0)
them.home()
them.left(90)

screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(jump,"Space")

screen.onkey(up2, "w")
screen.onkey(down2, "s")
screen.onkey(left2, "a")
screen.onkey(right2, "d")
screen.onkey(jump2,"x")
screen.listen()