Skip to content

Commit 102b1a4

Browse files
committed
Restored from older branch
1 parent 5c2177e commit 102b1a4

36 files changed

Lines changed: 2667 additions & 0 deletions

gems/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Gems Directory
2+
3+
Welcome to the "gems" directory! 🚀 Here, you'll find a collection of code snippets that serve as proof-of-concept (PoC) implementations. These snippets, while not directly used in the project, have been valuable in the development process. They've provided insights, solutions, or innovative approaches that have contributed to the overall success of the project.
4+
5+
## Purpose
6+
7+
- **Idea Exploration:** The snippets in this directory were created during the exploration phase, where various ideas and concepts were tested before implementation in the main project codebase.
8+
9+
- **Problem Solving:** These code snippets may contain solutions to specific challenges or problems encountered during development. While they might not be part of the final code, they showcase different approaches to problem-solving.
10+
11+
- **Learning and Experimentation:** The "gems" directory is also a space for experimentation and learning. Developers can refer to these PoCs to understand different techniques and methodologies.
12+
13+
## Organization
14+
15+
The directory is organized with each code snippet placed in a separate file or subdirectory, named descriptively to indicate its purpose or the problem it addresses. Additionally, a brief explanation is provided within each file to give context and insights into the PoC.
16+
17+
## How to Use
18+
19+
While the code in this directory is not directly integrated into the main project, you may find value in reviewing these snippets for reference or inspiration. If a particular PoC aligns with a current or future project requirement, feel free to adapt and incorporate the code into your work.
20+
21+
## Contributing
22+
23+
If you have additional PoCs or innovative code snippets that you believe could benefit the project, consider contributing them to this directory. Follow the contribution guidelines outlined in the project's main README.
24+
25+
## License
26+
27+
All code snippets in this directory are provided under the [project's license](https://github.com/poing/JS2PySecrets/blob/main/LICENSE). Please review the license before using or distributing any code from this directory.
28+
29+
Happy coding! 🎉

gems/dict2json.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# dict2json.py
6+
7+
"""
8+
This is a basic example of taking a Python dict and returning JSON.
9+
10+
The goal is passing function names and argument groups in a nested JSON.
11+
12+
It's a work in progress where the assumption is, there will be a set of setup commands (that are likely static), followed by a dynamic command with var based arguments.
13+
"""
14+
15+
import json
16+
17+
# key: value (the function & arguments)
18+
setup = [
19+
{"function": "setRNG", "args": ["testRandom"]},
20+
{"function": "init", "args": [12, 'testRandom']}
21+
]
22+
23+
# Dynamic Values
24+
foo = ["1234abc", 6, 3]
25+
26+
# key: value (the function & dynamic arguments)
27+
main = {"function": "share", "args": foo}
28+
29+
# Combine setup and main
30+
tasks = [{"setup": setup, "start": main}]
31+
32+
# Convert the Python dictionary to JSON
33+
json_data = json.dumps(tasks, indent=None)
34+
35+
# Print or use the JSON data as needed
36+
print(json_data)

gems/example1.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# example1.py
6+
7+
import json
8+
import js2pysecrets
9+
10+
# // generate a 512-bit key
11+
# key = js2pysecrets.random(512) // => key is a hex string
12+
key = js2pysecrets.random(512)
13+
print(key)
14+
15+
# // split into 10 shares with a threshold of 5
16+
# shares = js2pysecrets.share(key, 10, 5)
17+
# // => shares = ['801xxx...xxx','802xxx...xxx','803xxx...xxx','804xxx...xxx','805xxx...xxx']
18+
shares = js2pysecrets.share(key, 10, 5)
19+
print(shares)
20+
21+
# // combine 4 shares
22+
# var comb = secrets.combine(shares.slice(0, 4))
23+
# console.log(comb === key) // => false
24+
#
25+
# // combine 5 shares
26+
# comb = secrets.combine(shares.slice(4, 9))
27+
# console.log(comb === key) // => true
28+
#
29+
# // combine ALL shares
30+
# comb = secrets.combine(shares)
31+
# console.log(comb === key) // => true
32+
#
33+
# // create another share with id 8
34+
# var newShare = secrets.newShare(8, shares) // => newShare = '808xxx...xxx'
35+
#
36+
# // reconstruct using 4 original shares and the new share:
37+
# comb = secrets.combine(shares.slice(1, 5).concat(newShare))
38+
# console.log(comb === key) // => true

gems/example2.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# example1.py
6+
7+
import json
8+
import js2pysecrets
9+
10+
# var pw = "<<PassWord123>>"
11+
pw = "<<PassWord123>>"
12+
13+
# // convert the text into a hex string
14+
# var pwHex = secrets.str2hex(pw) // => hex string
15+
jsHex = js2pysecrets.str2hex(pw)
16+
print(jsHex)
17+
18+
pyHex = pw.encode('utf-16-be').hex().lstrip('fe')
19+
print(pyHex)
20+
21+
# // split into 5 shares, with a threshold of 3
22+
# var shares = secrets.share(pwHex, 5, 3)
23+
#
24+
# // combine 2 shares:
25+
# var comb = secrets.combine(shares.slice(1, 3))
26+
#
27+
# //convert back to UTF string:
28+
# comb = secrets.hex2str(comb)
29+
# console.log(comb === pw) // => false
30+
#
31+
# // combine 3 shares:
32+
# comb = secrets.combine([shares[1], shares[3], shares[4]])
33+
#
34+
# //convert back to UTF string:
35+
# comb = secrets.hex2str(comb)
36+
# console.log(comb === pw) // => true

gems/func2str.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# func2str.py
6+
7+
from functools import wraps
8+
import json
9+
10+
11+
def function_to_string(func):
12+
@wraps(func)
13+
def wrapper(*args, **kwargs):
14+
args_str = ', '.join(repr(arg) for arg in args)
15+
kwargs_str = ', '.join(f'{key}={repr(value)}' for key, value in kwargs.items())
16+
all_args = ', '.join(filter(None, [args_str, kwargs_str]))
17+
18+
return f"{func.__name__}({all_args});"
19+
20+
return wrapper
21+
22+
# Applying the decorator to functions
23+
@function_to_string
24+
def funcA(*args, **kwargs):
25+
pass
26+
27+
@function_to_string
28+
def funcB(*args, **kwargs):
29+
pass
30+
31+
funcC = function_to_string('blue')
32+
33+
# Testing
34+
print(funcA("aa", "bb", 123, x=123)) # "funcA('aa', 'bb', 123, x=123)"
35+
print(funcA('aa', 'bb', 123, x=123)) # "funcA('aa', 'bb', 123, x=123)"
36+
print(funcA('aa', 'bb', 123, x=123)) # "funcA('aa', 'bb', 123, x=123)"
37+
38+
# Support and pass dict
39+
print(funcB(["aa", "bb"], 123, x=123)) # 'funcB(["aa", "bb"], 123, x=123)'
40+
41+
foobar = "AAFF"
42+
43+
tasks = [
44+
funcA(foobar, 2, "that"),
45+
funcA(["some", "more", 2]),
46+
funcB("and something", "else", 2, plus=22),
47+
blue('hey'),
48+
]
49+
50+
# Convert the Python dictionary to JSON
51+
json_data = json.dumps(tasks, indent=None)
52+
53+
# Print or use the JSON data as needed
54+
print(json_data)
55+

gems/func2str2.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# func2str2.py
6+
7+
"""
8+
This script demonstrates making the JsFunction class work both as a callable and as a decorator.
9+
"""
10+
11+
class JsFunction:
12+
def __init__(self, func):
13+
self.func = func
14+
15+
def __call__(self, *args, **kwargs):
16+
def wrapped_func(*args, **kwargs):
17+
args_str = ', '.join(repr(arg) for arg in args)
18+
kwargs_str = ', '.join(f'{key}={repr(value)}'
19+
for key, value in kwargs.items())
20+
all_args = ', '.join(filter(None, [args_str, kwargs_str]))
21+
22+
return f"{self.func.__name__}({all_args})"
23+
24+
return wrapped_func(*args, **kwargs) if args else self.func(*args, **kwargs)
25+
26+
def __get__(self, instance, owner):
27+
return self if instance is None else types.MethodType(self, instance)
28+
29+
# Applied as a decorator
30+
# Functional placeholder that uses the JS code, until the Python function is created
31+
@JsFunction
32+
def alpha(*args, **kwargs):
33+
pass
34+
35+
# Eventually independent python function will be created
36+
def bravo():
37+
return "bravo('aa', 'bb', 123, x=123)"
38+
39+
# Create a alternately named instance of the JsFunction class that's callable
40+
# Which is important for testing against python functions
41+
testBravo = JsFunction(bravo)
42+
43+
"""
44+
WARNING - WARNING - WARNING - WARNING - WARNING - WARNING
45+
You cannot create an alternate instance using JsFunction it is already used. Attempting to do so may lead to unexpected behavior. For example, you cannot use testAlpha = JsFunction(alpha) if alpha() already has the JsFunction decorator applied.
46+
WARNING - WARNING - WARNING - WARNING - WARNING - WARNING
47+
"""
48+
49+
print(alpha("aa", "bb", 123, x=123)) # Returns: alpha('aa', 'bb', 123, x=123)
50+
print(bravo()) # Returns: bravo('aa', 'bb', 123, x=123)
51+
print(testBravo("aa", "bb", 123, x=123)) # Returns: bravo('aa', 'bb', 123, x=123)
52+
53+
def string_comparison(str1, str2):
54+
if str1 == str2:
55+
return "Test Passed: Strings are equal"
56+
else:
57+
return "Test Failed: Strings are not equal"
58+
59+
print(string_comparison(alpha(123,'aaa'), testBravo(123,'aaa')))
60+
print(string_comparison(bravo(), testBravo('aa', 'bb', 123, x=123)))

gems/func2str3.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# func2str3.py
6+
7+
"""
8+
This script demonstrates making the JsFunction class work both as a callable and as a decorator. Excluding **kwargs in the output. Added test flag.
9+
"""
10+
11+
class JsFunction:
12+
def __init__(self, func, test=False):
13+
self.func = func
14+
self.test = test
15+
16+
def __call__(self, *args, test=False, **kwargs):
17+
def wrapped_func(*args, **kwargs):
18+
args_str = ', '.join(repr(arg) for arg in args)
19+
#kwargs_str = ', '.join(f'{key}={repr(value)}'
20+
# for key, value in kwargs.items())
21+
#all_args = ', '.join(filter(None, [args_str, kwargs_str]))
22+
23+
return f"{self.func.__name__}({args_str})"
24+
25+
data = ["init()"]
26+
if test or self.test:
27+
data.append("setRNG('testRandom')")
28+
29+
data.append(wrapped_func(*args, **kwargs) if args else self.func(*args, **kwargs))
30+
return data
31+
32+
def __get__(self, instance, owner):
33+
return self if instance is None else types.MethodType(self, instance)
34+
35+
# Applied as a decorator
36+
# Functional placeholder that uses the JS code, until the Python function is created
37+
@JsFunction
38+
def alpha(*args, **kwargs):
39+
pass
40+
41+
# Eventually independent python function will be created
42+
def bravo():
43+
return "bravo('aa', 'bb', 123)"
44+
45+
# Create a alternately named instance of the JsFunction class that's callable
46+
# Which is important for testing against python functions
47+
testBravo = JsFunction(bravo, test=True)
48+
regBravo = JsFunction(bravo)
49+
50+
"""
51+
WARNING - WARNING - WARNING - WARNING - WARNING - WARNING
52+
You cannot create an alternate instance using the JsFunction if it is already used. Attempting to do so may lead to unexpected behavior. For example, you cannot use testAlpha = JsFunction(alpha) if alpha() already has the JsFunction decorator applied.
53+
WARNING - WARNING - WARNING - WARNING - WARNING - WARNING
54+
"""
55+
56+
print(alpha("aa", "bb", 123, x=123)) # Returns: alpha('aa', 'bb', 123, x=123)
57+
print(bravo()) # Returns: bravo('aa', 'bb', 123, x=123)
58+
print(testBravo("aa", "bb", 123, x=123)) # Returns: bravo('aa', 'bb', 123, x=123)
59+
print(regBravo("aa", "bb", 123, x=123)) # Returns: bravo('aa', 'bb', 123, x=123)
60+
61+
def string_comparison(str1, str2):
62+
if str1 == str2:
63+
return "Test Passed: Strings are equal"
64+
else:
65+
return "Test Failed: Strings are not equal"
66+
67+
print(string_comparison(alpha(123,'aaa'), testBravo(123,'aaa')))
68+
print(string_comparison(bravo(), testBravo('aa', 'bb', 123, x=123)))

gems/proc_commV1.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#! /usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# vim: set et sw=4 fenc=utf-8:
4+
#
5+
# proc_commV1.py
6+
7+
# Trying to use process.communicate() with Node
8+
9+
import subprocess
10+
11+
#JS_FILE_PATH = "wrapperV7.js"
12+
#js_command = ["node", "-i", JS_FILE_PATH]
13+
14+
# Start the Node.js process
15+
node_process = subprocess.Popen(["node", "-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
16+
17+
# Send JavaScript commands
18+
commands = [
19+
"const secrets = require('../secrets.js/secrets.js')",
20+
"console.log('Hello from Node.js!')",
21+
"console.log(2 + 2)",
22+
"console.log(Math.random())",
23+
"var HHGTTG = 42",
24+
"console.log(HHGTTG)",
25+
"secrets.share('1234abc', 6, 3)"
26+
]
27+
28+
29+
# Send commands to the Node.js process
30+
for command in commands:
31+
node_process.stdin.write(command + '\n')
32+
33+
# Read output
34+
output, error = node_process.communicate()
35+
36+
# Close stdin to indicate end of input
37+
node_process.stdin.close()
38+
39+
print("Output:")
40+
print(output)
41+
42+
print("Error:")
43+
print(error)

0 commit comments

Comments
 (0)