Skip to content

Instantly share code, notes, and snippets.

@lmyyao
lmyyao / base64_encode.py
Created October 25, 2024 10:43
base64 encode
def base64_unit(input_bytes):
base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
padding = {1: 2, 2: 1, 0: 0}[len(input_bytes) % 3]
while len(input_bytes) < 3:
input_bytes += b'\x00'
num = int.from_bytes(input_bytes, byteorder='big')
o = []
count = 0
@lmyyao
lmyyao / proxy.py
Created September 24, 2024 07:36
splice system call implement socket proxy
import socket
import select
import os
import fcntl
import threading
buffer_size = 1024
@lmyyao
lmyyao / client.py
Created August 22, 2024 09:29
file descriptor share across process
import socket
import os
import array
def send_fd(sock, fd):
"""Send a file descriptor to another process via a Unix domain socket."""
fds = array.array("i", [fd])
sock.sendmsg([b"x"], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
@lmyyao
lmyyao / client.py
Created August 21, 2024 09:09
macos socket so_reuseport does not work
import socket
import select
def test():
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(("", 8877))
c.send(b"hello world")
@lmyyao
lmyyao / sidh.sage
Created July 29, 2024 02:58
SIDH key exchange
### SIDH
### https://nbviewer.org/url/defeo.lu/docet/assets/jupyter/2018-03-22-PostScryptum.ipynb
p = 431
F.<i> = GF(p^2, modulus=x^2+1)
E = EllipticCurve(F, [1, 0])
E.order() == (p+1)^2
@lmyyao
lmyyao / schnorr.py
Created June 13, 2024 08:57
schnorr signature
import random
import hashlib
p = 2**256-2**32-977
g = 2
sk = random.randint(1, p-1)
pk = pow(g, sk, p)
@lmyyao
lmyyao / test_lwe.sage
Last active December 1, 2023 03:33
simple lwe demo
from sage.stats.distributions.discrete_gaussian_lattice import DiscreteGaussianDistributionLatticeSampler
def test_lwe(n, p, sigma, size=100):
F = GF(p)
a = random_vector(F, n)
HALF_P = int(p/2)
s = random_vector(F,n)
p41 = int(p/4)
p43 = int(p*3/4)
D = DiscreteGaussianDistributionLatticeSampler(F^1, sigma)
@lmyyao
lmyyao / kyber.sage
Created November 27, 2023 11:11
kyber kem demo
import numpy as np
P = next_prime(2^256)
N = 64
k = 16
BOUND = 32
HALF_P = int(P/2+0.5)
R.<x> = PolynomialRing(GF(P), 'x')
@lmyyao
lmyyao / pq_search.py
Created August 25, 2023 01:49
product quantization simlarity search demo
from scipy.cluster.vq import vq, kmeans
from scipy.spatial.distance import cdist
import numpy as np
class PQ(object):
def __init__(self, M, k):
self.M = M
self.k = k
def fit(self, vectors, iter=None):
@lmyyao
lmyyao / product_quantization.py
Created August 24, 2023 11:04
product_quantization demo
from scipy.cluster.vq import vq, kmeans
import numpy as np
class PQ(object):
def __init__(self, M, k):
self.M = M
self.k = k
def fit(self, vectors, iter=None):
assert vectors.ndim == 2, "vectors must be 2 dim array"