Sunday, January 14, 2018

mute an application

import os
import re
import sys

sindex = os.popen("pacmd list-sink-inputs")

sindexl ="\n")
loopstart = False
comm = sys.argv[1]
appname = sys.argv[2]
mindexx = 0
for i  in sindexl:
    # print [i]
    if"index: ", i):
        mindex = re.sub("index:","", i).strip()
        if, i.lower()):
            mindexx =mindex
print mindexx
if comm == "mute":
    os.system("pacmd set-sink-input-mute "+mindexx+" 1")
    print "muted"
elif comm =="unmute":
    os.system("pacmd set-sink-input-mute "+mindexx+" 0")
    print "muted"

1- usage

$ python mute vlc
$ python unmute vlc

Wednesday, January 10, 2018

convert between latitude longitude and georef

World Geographic Reference System (GEOREF)

import sys


def ll_2_georef( lat, lon ):
    f_lat, f_lon = lat+90, lon+180
    lat_0, lat_1 = divmod( int(f_lat), 15 )
    lon_0, lon_1 = divmod( int(f_lon), 15 )
    lat_m, lon_m = 6000*(f_lat-int(f_lat)), 6000*(f_lon-int(f_lon))
    return "{lon_0}{lat_0}{lon_1}{lat_1}{lon_m:04d}{lat_m:04d}". \
        lon_0= georef_uppercase[lon_0],
        lat_0= georef_uppercase[lat_0],
        lon_1= georef_uppercase[lon_1],
        lat_1= georef_uppercase[lat_1],
        lon_m= int(lon_m),
        lat_m= int(lat_m),

def georef_2_ll( grid ):
    lon_0, lat_0, lon_1, lat_1= grid[:4]

    rest= grid[4:]
    pos= len(rest)//2
    if pos:
        scale= { 4: 100, 3: 10, 2: 1 }[pos]
        lon_frac, lat_frac = float(rest[:pos])/scale,\
        lon_frac, lat_frac = 0, 0
    lat= georef_uppercase.find(lat_0)*15+georef_uppercase.\
    lon= georef_uppercase.find(lon_0)*15+georef_uppercase.\
    return lat-90, lon-180

#python 45.234  89.67
#python TKQA40201404

if len(sys.argv) == 2:
    georef1 = sys.argv[1]
    print georef1
elif len(sys.argv) > 2:
    lat = float(sys.argv[1])
    lon= float(sys.argv[2])
    print(lat, lon)
    print(ll_2_georef(lat, lon))

1- usage
$ python 45.234  89.67
$ python TKQA40201404


import random
from math import gcd

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 multiplicative_inverse(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
        return x % m

Tests to see if a number is prime.
def is_prime(num):
    if num == 2:
        return True
    if num < 2 or num % 2 == 0:
        return False
    for n in range(3, int(num**0.5)+2, 2):
        if num % n == 0:
            return False
    return True

def generate_keypair(p, q):
    if not (is_prime(p) and is_prime(q)):
        raise ValueError('Both numbers must be prime.')
    elif p == q:
        raise ValueError('p and q cannot be equal')
    #n = pq
    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
    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)

    #Use Extended Euclid's Algorithm to generate the private key
    d = multiplicative_inverse(e, phi)
    #Return public and private keypair
    #Public key is (e, n) and private key is (d, n)
    return ((e, n), (d, n))

def encrypt(pk, plaintext):
    #Unpack the key into it's components
    key, n = pk
    #Convert each letter in the plaintext to numbers based on the character using a^b mod m
    cipher = [(ord(char) ** key) % n for char in plaintext]
    #Return the array of bytes
    return cipher

def decrypt(pk, ciphertext):
    #Unpack the key into its components
    key, n = pk
    #Generate the plaintext based on the ciphertext and key using a^b mod m
    plain = [chr((char ** key) % n) for char in ciphertext]
    #Return the array of bytes as a string
    return ''.join(plain)

if __name__ == '__main__':
    Detect if the script is being run directly by the user
#    print "RSA Encrypter/ Decrypter"
    p = int(input("Enter a prime number (17, 19, 23, etc): "))
    q = int(input("Enter another prime number (Not one you entered above): "))
#    print "Generating your public/private keypairs now . . ."
    public, private = generate_keypair(p, q)
    print ("Your public key is ", public ," and your private key is ", private)
    message = input("Enter a message to encrypt with your private key: ")
    encrypted_msg = encrypt(private, message)
#    print "Your encrypted message is: "
    print (''.join(map(lambda x: str(x), encrypted_msg)))
    print ("Decrypting message with public key ", public ," . . .")
#    print "Your message is:"
    print (decrypt(public, encrypted_msg))

otp , one-time pad

import binascii
import random
import sys
import re

def genpad(padlen):
    pad = ""
    for i in range(0,padlen):
        pad +=chr(random.randint(0,255))
    return pad

def otp(text, chars):
    hextext = binascii.hexlify(text)
    xorres = ""
    n = 1
    for i,j in zip(text,chars):
        xorout = chr(int(bin(ord(i) ^ ord(j)),2))
        xorres += xorout
        n +=1
    return xorres

def deotp(text,chars):
    hextext = binascii.hexlify(text)
    xorres = ""
    n = 1
    for i,j in zip(text,chars):

        xorout = chr(int(bin(ord(i) ^ ord(j)),2))

        xorres += xorout
        n +=1
    return xorres

if sys.argv[1]=="encrypt":
    inputfile = sys.argv[2]
    padname = sys.argv[3]

    with open(inputfile) as f:
        fr =
        # print fr
        yourpad = genpad(len(fr))
        ciphertext = otp(fr,yourpad)

    with open(inputfile+".enc", "wr") as f:
        print "the encrpyted text saved in " + inputfile + ".enc"

    with open(padname,"wr") as f:
        print "your pad is save to " + padname
        print "pls keep it."

if sys.argv[1]=="decrypt":
    inputfile = sys.argv[2]
    # output = re.sub(r"\.enc$"inputfile)
    padname = sys.argv[3]
    with open(padname,"r") as f:
        pad =

    with open(inputfile) as f:
        fr =
        secfile = otp(fr,pad)
    with open(inputfile+".dec", "wr") as f:
        print "the decrpyted text saved in " + inputfile + ".dec"

1- usage
- padfile, is use to save the pad
$ otp encrypt inputfile padfile

- decypt
$ opt decrypt inputfile padfile

Sunday, January 7, 2018

emulate a flashdrive in qemu

1- create usbstick image

- if raw type
$ qemu-img create -f raw -o size=1G test.raw

-if qcow2 type

$ qemu-img create -f qcow2 -o size=1G test.cow2

2- create file system

if need to create partition use fdisk test.raw
-or to formate as ext4 file system
$ mkfs.ext4 test.raw

3- to test we can just to tinycore live cd, download from

- execute
$ qemu-system-x86_64 -drive if=none,id=usbstick,file=/home/use1/test.raw -usb -device usb-ehci,id=ehci   \
        -device usb-storage,bus=ehci.0,drive=usbstick -m 2048 -hdc /home/tun/Downloads/TinyCore-current.iso

- the usb will be in /dev/sdb, so we can mount it to use
$ mount /dev/sdb /mnt