From 7980bc68c455d496233dbbcc9d9ec70c1352e13f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Radoslav=20Bod=C3=B3?= <bodik@cesnet.cz>
Date: Mon, 25 Mar 2024 13:42:14 +0100
Subject: [PATCH] rclone crypt: refactor obscure to use cryptography package

---
 Makefile         |  9 ++++++++-
 requirements.txt |  2 +-
 rwm.py           | 12 +++++++-----
 3 files changed, 16 insertions(+), 7 deletions(-)

diff --git a/Makefile b/Makefile
index c4f70ca..71fd0ed 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
 all: lint
 
 install:
-	apt-get -y install awscli make rclone yamllint
+	apt-get -y install awscli make python3-cryptography rclone yamllint
 
 venv:
 	apt-get -y install python3-venv
@@ -9,6 +9,13 @@ venv:
 	venv/bin/pip install -U pip
 	venv/bin/pip install -r requirements.lock
 
+venv-refresh:
+	apt-get -y install python3-venv
+	rm -r venv
+	python3 -m venv venv
+	venv/bin/pip install -U pip
+	venv/bin/pip install -r requirements.txt
+
 freeze:
 	@pip freeze | grep -v '^pkg[-_]resources='
 
diff --git a/requirements.txt b/requirements.txt
index 0020f1c..98717c2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,5 +1,5 @@
 # runtime
-pycryptodome
+cryptography
 
 # dev
 flake8
diff --git a/rwm.py b/rwm.py
index 5e7cf77..49e3c5d 100755
--- a/rwm.py
+++ b/rwm.py
@@ -10,8 +10,8 @@ from pathlib import Path
 from subprocess import run as subrun
 
 import yaml
-from Crypto.Cipher import AES
-from Crypto.Random import get_random_bytes
+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
+from cryptography.hazmat.backends import default_backend
 
 
 def is_sublist(needle, haystack):
@@ -36,11 +36,13 @@ def rclone_obscure_password(plaintext, iv=None):
 
     # https://github.com/rclone/rclone/blob/master/fs/config/obscure/obscure.go
     # https://github.com/maaaaz/rclonedeobscure
+    # GTP translate to python cryptography
+
     secret_key = b"\x9c\x93\x5b\x48\x73\x0a\x55\x4d\x6b\xfd\x7c\x63\xc8\x86\xa9\x2b\xd3\x90\x19\x8e\xb8\x12\x8a\xfb\xf4\xde\x16\x2b\x8b\x95\xf6\x38"
     if not iv:
-        iv = get_random_bytes(AES.block_size)
-    cipher = AES.new(key=secret_key, mode=AES.MODE_CTR, initial_value=iv, nonce=b'')
-    data = iv + cipher.encrypt(plaintext.encode())
+        iv = os.urandom(16)
+    encryptor = Cipher(algorithms.AES(secret_key), modes.CTR(iv), backend=default_backend()).encryptor()
+    data = iv + encryptor.update(plaintext.encode()) + encryptor.finalize()
     return base64.urlsafe_b64encode(data).decode().rstrip("=")
 
 
-- 
GitLab