]> _ Git - cubist_util.git/commitdiff
wip #4793 @0:10
authorVincent Vanwaelscappel <vincent@cubedesigners.com>
Thu, 14 Oct 2021 19:11:12 +0000 (21:11 +0200)
committerVincent Vanwaelscappel <vincent@cubedesigners.com>
Thu, 14 Oct 2021 19:11:12 +0000 (21:11 +0200)
composer.json
src/Crypt.php [new file with mode: 0644]

index 1a7fa8754ddc91063cd0ab5c1b485aa8506b54ce..b8cebe0b907682b5d468b103201de76254f7997a 100644 (file)
@@ -22,7 +22,7 @@
     }
   ],
   "require": {
-    "php": ">=7.0.0",
+    "php": ">=7.2",
     "ext-libxml": "*",
     "ext-mbstring": "*",
     "ext-dom": "*",
@@ -30,7 +30,8 @@
     "ext-json": "*",
     "ext-iconv": "*",
     "laravel/framework": "~5.8|^6.0|^7.0|^8.0",
-    "cubist/net": "dev-master"
+    "cubist/net": "dev-master",
+    "ext-sodium": "*"
   }
 }
 
diff --git a/src/Crypt.php b/src/Crypt.php
new file mode 100644 (file)
index 0000000..cb04b41
--- /dev/null
@@ -0,0 +1,60 @@
+<?php
+
+namespace Cubist\Util;
+
+use Exception;
+
+class Crypt
+{
+    /**
+     * @throws \SodiumException
+     * @throws Exception
+     */
+    public static function safeEncrypt($message, $key)
+    {
+        $nonce = random_bytes(
+            SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
+        );
+
+        $cipher = base64_encode(
+            $nonce .
+            sodium_crypto_secretbox(
+                $message,
+                $nonce,
+                $key
+            )
+        );
+        sodium_memzero($message);
+        sodium_memzero($key);
+        return $cipher;
+    }
+
+    /**
+     * @throws \SodiumException
+     * @throws Exception
+     */
+    public static function safeDecrypt($encrypted, $key)
+    {
+        $decoded = base64_decode($encrypted);
+        if ($decoded === false) {
+            throw new Exception('Scream bloody murder, the encoding failed');
+        }
+        if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
+            throw new Exception('Scream bloody murder, the message was truncated');
+        }
+        $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
+        $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
+
+        $plain = sodium_crypto_secretbox_open(
+            $ciphertext,
+            $nonce,
+            $key
+        );
+        if ($plain === false) {
+            throw new Exception('the message was tampered with in transit');
+        }
+        sodium_memzero($ciphertext);
+        sodium_memzero($key);
+        return $plain;
+    }
+}
\ No newline at end of file