1660107541
Rclone ("rsync for cloud storage") is a command-line program to sync files and directories to and from different cloud storage providers.
Please see the full list of all storage providers and their features
These backends adapt or modify other storage providers
Please see the rclone website for:
Author: rclone
Source Code: https://github.com/rclone/rclone
License: MIT license
1660034460
libnettle
supports a wide array of hashing algorithms. This package interrogates libnettle
to determine the available hash types, which are then available from Nettle.get_hash_types()
. Typically these include SHA1
, SHA224
, SHA256
, SHA384
, SHA512
, MD2
, MD5
and RIPEMD160
.
Typical usage of these hash algorithms is to create a Hasher
, update!
it, and finally get a digest
:
h = Hasher("sha256")
update!(h, "this is a test")
hexdigest!(h)
#or...
hexdigest("sha256", "this is a test")
Outputs:
2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c
A digest!
function is also available to return the digest as an Array(UInt8,1)
. Note that both the digest!
function and the hexdigest!
function reset the internal Hasher
object to a pristine state, ready for further update!
calls.
HMAC Functionality
HMAC functionality revolves around the HMACState
type, created by the function of the same name. Arguments to this constructor are the desired hash type, and the desired key used to authenticate the hashing:
h = HMACState("sha256", "mykey")
update!(h, "this is a test")
hexdigest!(h)
#or...
hexdigest("sha256", "mykey", "this is a test")
Outputs:
"ca1dcafe1b5fb329256248196c0f92a95fbe3788db6c5cb0775b4106db437ba2"
A digest!
function is also available to return the digest as an Array(UInt8,1)
. Note that both the digest!
function and the hexdigest!
function reset the internal HMACState
object to a pristine state, ready for further update!
calls.
Encryption/Decryption Functionality
Nettle also provides encryption and decryption functionality, using the Encryptor
and Decryptor
objects. Cipher types are available through get_cipher_types()
. Create a pair of objects with a shared key, and encrypt()
/decrypt()
to your heart's content:
key = "this key's exactly 32 bytes long"
enc = Encryptor("AES256", key)
plaintext = "this is 16 chars"
ciphertext = encrypt(enc, plaintext)
dec = Decryptor("AES256", key)
deciphertext = decrypt(dec, ciphertext)
Vector{UInt8}(plaintext) == deciphertext # no bytestring
# or...
decrypt("AES256", key, encrypt("AES256", key, plaintext)) == Vector{UInt8}(plaintext)
For AES256CBC encrypt/decrypt, generate a pair of key32 and iv16 with salt.
(And add or trim padding yourself.)
passwd = "Secret Passphrase"
salt = hex2bytes("a3e550e89e70996c") # use random 8 bytes
(key32, iv16) = gen_key32_iv16(Vector{UInt8}(passwd), salt)
enc = Encryptor("AES256", key32)
plaintext = "Message"
ciphertext = encrypt(enc, :CBC, iv16, add_padding_PKCS5(Vector{UInt8}(plaintext), 16))
dec = Decryptor("AES256", key32)
deciphertext = decrypt(dec, :CBC, iv16, ciphertext)
Vector{UInt8}(plaintext) == trim_padding_PKCS5(deciphertext) # no bytestring
# or...
plainbytes = hex2bytes("414155aa5541416162")
cipherbytes = encrypt("AES256", :CBC, iv16, key32, add_padding_PKCS5(plainbytes, 16))
decipherbytes = decrypt("AES256", :CBC, iv16, key32, cipherbytes)
plainbytes == trim_padding_PKCS5(decipherbytes) # no bytestring
Author: JuliaCrypto
Source Code: https://github.com/JuliaCrypto/Nettle.jl
License: View license
1658404920
mz_rsa_plugin
Flutter RSA Encryption & Decryption(Flutter RSA 加密和解密)
To use the plugin ,add mz_rsa_plugin
as a dependency in your pubspec.yaml
//Encrypt string by public key,the public key is String (使用公钥加密字符串,公钥是字符串)
var str1 = await MzRsaPlugin.encryptStringByPublicKey(originText, PUBLICK_KEY);
// Decrypt the encrypted string by private key, the private key is String(使用私钥解密公钥加密过的字符串,私钥是字符串)
var str2 = await MzRsaPlugin.decryptStringByPrivateKey(str1, PRIVART_KEY);
//Encrypt string by private key,the private key is String (使用私钥加密字符串,私钥是字符串)
var str3 = await MzRsaPlugin.encryptStringByPrivateKey(originText, PRIVART_KEY);
// Decrypt the encrypted string by public key, the public key is String(使用公钥解密私钥加密过的字符串,公钥是字符串)
var str4 = await MzRsaPlugin.decryptStringByPublicKey(str3, PUBLICK_KEY);
Please see the example of this plugin for a full example
Run this command:
With Flutter:
$ flutter pub add mz_rsa_plugin
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
mz_rsa_plugin: ^0.0.4
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:mz_rsa_plugin/mz_rsa_plugin.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:mz_rsa_plugin/mz_rsa_plugin.dart';
const String PUBLICK_KEY =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArdklK4kIsOMuxTZ8jG1PRPfXqSDmaCIQ+xEpIRSssQ6jiuvhYZTMUbV22osgtivuyKdnHm+cvzGuZCSB8QFyCcM7l09HZVs0blLkrBAU5CVSv+6BzPQTVJytoi/VO4mlf6me1Y9bXWrrPw1YtC1mnB2Ix9cuaxOLpucglfGbUaGEigsUZMTD2vuEODN5cJi39ap+G9ILitbrnt+zsW9354pokVnHw4Oq837Fd7ZtP0nAA5F6nE3FNDGQqLy2WYRoKC9clDecD8T933azUD98b5FSUGzIhwiuqHHeylfVbevbBW91Tvg9s7vUMr0Y2YDpEmPAf0q4PlDt8QsjctT9kQIDAQAB";
const String PRIVART_KEY =
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCt2SUriQiw4y7FNnyMbU9E99epIOZoIhD7ESkhFKyxDqOK6+FhlMxRtXbaiyC2K+7Ip2ceb5y/Ma5kJIHxAXIJwzuXT0dlWzRuUuSsEBTkJVK/7oHM9BNUnK2iL9U7iaV/qZ7Vj1tdaus/DVi0LWacHYjH1y5rE4um5yCV8ZtRoYSKCxRkxMPa+4Q4M3lwmLf1qn4b0guK1uue37Oxb3fnimiRWcfDg6rzfsV3tm0/ScADkXqcTcU0MZCovLZZhGgoL1yUN5wPxP3fdrNQP3xvkVJQbMiHCK6ocd7KV9Vt69sFb3VO+D2zu9QyvRjZgOkSY8B/Srg+UO3xCyNy1P2RAgMBAAECggEAInVN9skcneMJ3DEmkrb/5U2yw2UwBifqcbk/C72LVTTvmZOTgsH5laCARGUbQMCIfeEggVniGcuBI3xQ/TIqJmE6KI2gOyjOxadMiAZP/cCgHEbsF3Gxey3rBKCyhTCNSzaVswLNO0D8C+1bTatKEVuRRvsRykt/fL+HJ/FRteYYO9LuLv2WESJGE6zsi03P6snNiRracvYqz+Rnrvf1Xuyf58wC1C6JSjZ9D6tootPDBTEYaIIbpEnV+qP/3k5OFmA9k4WbkZI6qYzqSK10bTQbjMySbatovnCD/oqIUOHLwZpL051E9lz1ZUnDbrxKwT0BIU7y4DYaHSzrKqRsIQKBgQDTQ9DpiuI+vEj0etgyJgPBtMa7ClTY+iSd0ccgSE9623hi1CHtgWaYp9C4Su1GBRSF0xlQoVTuuKsVhI89far2Z0hR9ULr1J1zugMcNESaBBC17rPoRvXPJT16U920Ntwr00LviZ/DEyvmpVDagYy+mSK0Wq+kH7p5aR5zAHXWrQKBgQDSqQ6TBr5bDMvhpRi94unghiWyYL6srSRV9XjqDpiNU+yFwCLzSG610DyXFa3pV138P+ryunqg1LtKsOOtZJONzbS1paINnwkvfwzMpI7TjCq1+8rxeEhZ3AVmumDtPQK+YfGbxCQ+LAOJZOu8lGv1O7tsbXFp0vh5RmWHWHvy9QKBgCMGPi9JsCJ4cpvdddQyizLk9oFxwAlMxx9G9P08H7kdg4LW6l0Gs+yg/bBf86BFHVbmXW8JoBwHj418sYafO+Wnz8yOna6dTBEwiG13mNvzypVu4nKiuQPDh8Ks/rdu1OeLGbC+nzbnCcMuKw5epee/WYqO8kmCXRbdv4ePTvntAoGBAJYQ9F7saOI3pW2izJNIeE8HgQcnP+2GkeHiMjaaGzZiWJWXH86rBKLkKqV+PhuBr2QorFgpW34CzUER7b7xbOORbHASA/UsG8EIArgtacltimeFbTbC9td8kyRxFOcrlS7GWvUZrq/TbtmLWRtHp/hUitlcxXQbZAIQkfbuo62ZAoGBAKBURvLGM0ethkvUHFyGae2YGG/s+u+EYd2zNba7A6qnfzrlMHVPiPO6lx31+HwhuJ0tBZWMJKhEZ5PWByZzreVKVH5fE5LoQLo+B3VCTyTc1fJ9RKLAPrPqHuvzPHHP/n84XHGeit3e4ytd3Mm/6CNbrg7xux2M4RDQmN//1UOY";
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var originText = "hello hello hello hello hello";
var publicKeyEncryptText = "";
var privateKeyDecryptText = "";
var privateKeyEncryptText = "";
var publicKeyDecryptText = "";
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
var str1 =
await MzRsaPlugin.encryptStringByPublicKey(originText, PUBLICK_KEY);
var str2 = await MzRsaPlugin.decryptStringByPrivateKey(str1, PRIVART_KEY);
var str3 =
await MzRsaPlugin.encryptStringByPrivateKey(originText, PRIVART_KEY);
var str4 = await MzRsaPlugin.decryptStringByPublicKey(str3, PUBLICK_KEY);
print(str1);
print(str2);
print(str3);
print(str4);
setState(() {
this.publicKeyEncryptText = str1;
this.privateKeyDecryptText = str2;
this.privateKeyEncryptText = str3;
this.publicKeyDecryptText = str4;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: ListView(
children: [
Text(
"加密前数据:$originText",
style: TextStyle(fontSize: 16),
),
SizedBox(
height: 20,
),
Text(
"公钥加密原数据后:$publicKeyEncryptText",
style: TextStyle(fontSize: 16),
),
SizedBox(
height: 20,
),
Text(
"私钥解密公钥加密后的数据:$privateKeyDecryptText",
style: TextStyle(fontSize: 16),
),
SizedBox(
height: 20,
),
Text(
"私钥加密原数据后:$privateKeyEncryptText",
style: TextStyle(fontSize: 16),
),
SizedBox(
height: 20,
),
Text(
"公钥解密私钥加密后的数据:$publicKeyDecryptText",
style: TextStyle(fontSize: 16),
),
SizedBox(
height: 20,
),
],
),
),
);
}
}
Download Details:
Author: 1691665955
Source Code: https://github.com/1691665955/mz_rsa_plugin
1656584580
Serverless-s3-encryption
set or remove the encryption settings on the s3 buckets in your serverless stack
This plugin runs on the after:deploy
hook, but you can also run it manually with: sls s3-encryption update
npm install --save-dev serverless-s3-encryption
See the example below for how to modify your serverless.yml
# serverless.yml
plugins:
# ...
- serverless-s3-encryption
custom:
# ...
s3-encryption:
buckets:
MyEncryptedBucket:
# see: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketEncryption-property
# accepted values: none, AES256, aws:kms
SSEAlgorithm: AES256
# only if SSEAlgorithm is aws:kms
KMSMasterKeyID: STRING_VALUE
resources:
Resources:
MyEncryptedBucket:
Type: "AWS::S3::Bucket"
Description: my encrypted bucket
DeletionPolicy: Retain
Author: Tradle
Source Code: https://github.com/tradle/serverless-s3-encryption
License:
1653980460
In this video we will see how to create and work with a SQLCipher encrypted database in .NET MAUI. The code that is shown will also still work with Xamarin.Forms. I will walk you through the existing code I created in a previous video with the CRUD actions for SQLite and then proceed with how to encrypt your database with sqlite-net-sqlcipher.
Disclaimer: this channel is done on personal title, in my free time, and not officially affiliated with or endorsed by Microsoft (my employer) in any way. Opinions and views are my own.
🔗 Links
Sample App Repo: https://github.com/jfversluis/MauiEncryptedSqliteSample
SQLite/SQLCipher compatibility: https://github.com/praeclarum/sqlite-net/issues/955
⏱ Timestamps
00:00 - Encrypt SQLite Database with .NET MAUI
00:13 - STOP! Do This First...
01:24 - SQLite CRUD App Sample
04:20 - Implement SQLite Encryption
08:02 - A Note About Compatibility
10:53 - What Should I Know More?!
12:00 - Want To Learn More?
1651133583
En este artículo hablaremos del Cifrado Homomórfico, el problema que resuelve y los diferentes tipos que existen.
Luego escribiremos código en Python para mostrar algunas de sus capacidades en acción.
El nombre homomórfico proviene del término algebraico homomorfismo.
"El homomorfismo es un mapa que conserva la estructura entre dos estructuras algebraicas del mismo tipo (como dos grupos, dos anillos o dos espacios vectoriales)". (Fuente: Wikipedia)
Homomorphic Encryption
es una forma de cifrado que permite a los usuarios realizar operaciones binarias en datos cifrados sin siquiera descifrar los datos.
Esta forma de encriptación permite encriptar la información y subcontratarla a servicios/entornos en la nube para su procesamiento, sin acceder a los datos sin procesar.
En el mundo actual, si queremos realizar cálculos sobre datos cifrados, como operaciones matemáticas, primero tenemos que descifrarlos. Luego tenemos que hacer nuestros cálculos y, finalmente, cifrar los datos de nuevo para enviarlos de vuelta.
Pero, ¿qué sucede cuando los datos cifrados son muy sensibles y no queremos que otros servicios tengan acceso a ellos? Aquí es donde Homomorphic encryption
entra en juego.
Un ejemplo más práctico sería un sistema/servicio que procesa información médica para diagnosticar si un paciente tiene una condición o no.
Los datos que estaríamos compartiendo probablemente incluyan información muy confidencial sobre el historial médico del paciente. Así que esto es algo que queremos asegurarnos de que nadie más pueda acceder a él.
Usando Homomorphic Encryption
, el sistema/servicio puede procesar los cálculos requeridos sobre los datos cifrados, devolviendo el resultado del diagnóstico sin saber qué información se está procesando.
Compartir información sensible a través de diferentes plataformas delata nuestra privacidad. Por otro lado, poder modificar y realizar operaciones sobre los datos mientras están encriptados garantiza la privacidad de los datos.
El objetivo del cifrado homomórfico es el siguiente: dada cualquier entrada comoinput := Enc(x1),...,Enc(xn)
, para cualquier función arbitraria f
que aplique un número infinito de sumas o multiplicaciones como value := f(Enc(x1),...,Enc(xn))
, el valor puede calcularse mientras la entrada está cifrada.
Las operaciones aritméticas, al fin y al cabo, se implementan a nivel de hardware (como cualquier otra cosa) bajo circuitos aritméticos o booleanos.
Las operaciones que queremos realizar son la Suma Homomórfica y la Multiplicación Homomórfica. Los nombres Suma y Multiplicación se dan debido al comportamiento similar de la suma binaria y la multiplicación binaria que tienen las puertas lógicas XOR y AND correspondientemente. La combinación de estas dos puertas puede representar cualquier función booleana.
Los factores hacen que la complejidad varíe en función del número y el tipo de operaciones.
Debido a estas restricciones y al problema de construir un algoritmo de cifrado totalmente homomórfico (que admita tanto la suma homomórfica como la multiplicación homomórfica), con el tiempo se han implementado diferentes esquemas.
Los tipos más comunes de cifrado homomórfico son:
El cifrado homomórfico parcial (PHE) permite que solo se realice una operación en el texto cifrado un número infinito de veces. Esta operación puede ser solo suma o solo multiplicación.
Los algoritmos de cifrado parcialmente homomórfico son más fáciles de diseñar y son muy útiles en aplicaciones que utilizan una operación aritmética.
El cifrado algo homomórfico (SHE) permite realizar sumas y multiplicaciones, pero por un número limitado de veces. Esta limitación se evalúa con cierta profundidad en la lógica del circuito. Este es un hito muy importante para alcanzar el cifrado totalmente homomórfico.
El cifrado completamente homomórfico (FHE) permite realizar sumas y multiplicaciones en el texto cifrado una cantidad infinita de veces, lo que admite cálculos arbitrarios en datos cifrados.
El principal problema con el cifrado totalmente homomórfico es la rentabilidad tanto en términos de velocidad como de requisitos de almacenamiento en comparación con las operaciones de texto sin formato.
El criptosistema Paillier fue inventado por Pascal Paillier en 1999. Es un esquema de cifrado homomórfico parcial (PHE) y homomórfico aditivo.
Solo admite la adición de dos textos cifrados y no la multiplicación entre ellos. Además, se puede agregar o multiplicar un número de texto sin formato al texto cifrado.
En este ejemplo, usamos python-paillier
, una biblioteca de Python para el cifrado parcialmente homomórfico utilizando el sistema criptográfico Paillier.
from phe import paillier
num1 = 10
num2 = 20
pub_key, priv_key = paillier.generate_paillier_keypair()
cipher_num1, cipher_num2 = pub_key.encrypt(num1), pub_key.encrypt(num2)
# add two encrypted numbers together
result = cipher_num1 + cipher_num2
result = priv_key.decrypt(result)
print("add two encrypted numbers together:",result)
# add an encrypted number to a plaintext number
result = cipher_num1 + 5
result = priv_key.decrypt(result)
print("add an encrypted number to a number:",result)
# multiply an encrypted number by a plaintext number
result = cipher_num1 * 10
result = priv_key.decrypt(result)
print("multiply an encrypted number to a number:",result)
En el ejemplo anterior, generamos un par de claves de una clave pública y una privada. A continuación, ciframos ambos con la clave pública y realizamos num1
operaciones num2
en sus textos cifrados.
Primero, agregamos los dos cifrados. Después de eso, tomamos cipher_num1
y le agregamos un número de texto sin formato. Por último, hicimos el mismo proceso que antes, pero en lugar de sumar, cipher_num1
esta vez multiplicamos con un número de texto sin formato.
El cálculo de estas operaciones se realiza mientras los datos están encriptados. Además, podemos verificar la integridad del resultado cada vez descifrándolo usando la clave privada.
El cifrado homomórfico (HE) parece un sueño cuando se trata de privacidad y protección de datos. Pero su bajo rendimiento y altos costos aún lo mantienen fuera de las aplicaciones comerciales/de producción.
Pero ha habido muchas mejoras en términos de velocidad últimamente. Con el ritmo actual, creo que se irá adaptando a nivel mundial durante los próximos años.
Fuente: https://www.freecodecamp.org/news/introduction-to-homomorphic-encryption/
1651123394
この記事では、準同型暗号化、それが解決する問題、および存在するさまざまなタイプについて説明します。
次に、Pythonでコードを記述して、その機能の一部を実際に示します。
準同型という名前は、代数用語の準同型に由来します。
「準同型は、同じタイプの2つの代数的構造(2つのグループ、2つのリング、2つのベクトル空間など)間の構造保存マップです。」(出典:ウィキペディア)
Homomorphic Encryption
は、ユーザーがデータを復号化することなく、暗号化されたデータに対して二項演算を実行できるようにする暗号化の形式です。
この形式の暗号化により、生データにアクセスすることなく、情報を暗号化してクラウドサービス/環境にアウトソーシングして処理することができます。
今日の世界では、数学演算などの暗号化されたデータに対して計算を実行する場合は、最初にそれらを復号化する必要があります。次に、計算を行い、最後にデータを再度暗号化して返送する必要があります。
しかし、暗号化されたデータが非常に機密性が高く、他のサービスがそれらにアクセスすることを望まない場合はどうなりますか?ここで効果がありHomomorphic encryption
ます。
より実用的な例は、患者が状態を持っているかどうかを診断するために医療情報を処理するシステム/サービスです。
共有するデータには、おそらく患者の病歴に関する非常に機密性の高い情報が含まれています。したがって、これは他の人がアクセスできないようにするためのものです。
を使用するHomomorphic Encryption
と、システム/サービスは暗号化されたデータに対して必要な計算を処理し、どの情報が処理されているかを知らなくても診断結果を返すことができます。
さまざまなプラットフォームを介して機密情報を共有すると、プライバシーが失われます。一方、データが暗号化されている間にデータを変更および操作できることで、データのプライバシーが確保されます。
準同型暗号化の目的は次のとおりです。などの入力が与えられると、などの無限の数の加算または乗算を適用するinput := Enc(x1),...,Enc(xn)
任意の関数に対して、入力が暗号化されている間に値を計算できます。fvalue := f(Enc(x1),...,Enc(xn))
一日の終わりに、算術演算は、算術回路またはブール回路の下でハードウェアレベルで(他のものと同様に)実装されます。
実行したい操作は、準同型加算と準同型乗算です。AdditionとMultiplicationという名前は、論理ゲートXORとANDが対応して持つバイナリ加算とバイナリ乗算の動作が似ているために付けられています。これらの2つのゲートの組み合わせは、任意のブール関数を表すことができます。
これらの要因により、操作の数と種類に基づいて複雑さが変化します。
これらの制限と完全な準同型暗号化アルゴリズム(準同型加算と準同型乗算の両方をサポート)を構築する問題のために、時間の経過とともにさまざまなスキームが実装されてきました。
準同型暗号化の最も一般的なタイプは次のとおりです。
部分準同型暗号化(PHE)では、暗号文に対して1つの操作のみを無限に実行できます。この操作は、加算のみまたは乗算のみにすることができます。
部分準同型暗号化アルゴリズムは設計が簡単で、1つの算術演算を使用するアプリケーションで非常に役立ちます。
ある程度準同型暗号化(SHE)を使用すると、加算と乗算の両方を実行できますが、回数は限られています。この制限は、回路ロジックの特定の深さまで評価されます。これは、完全準同型暗号化に到達するための非常に重要なマイルストーンです。
完全準同型暗号化(FHE)を使用すると、暗号文に対して加算と乗算の両方を無限に実行でき、 暗号化されたデータに対する任意の計算をサポートします。
完全準同型暗号化の主な問題は、平文操作と比較して、速度とストレージ要件の両方の点でコスト効率です。
Paillier Cryptosystemは、1999年にPascal Paillierによって発明されました。これは、部分準同型暗号化(PHE)スキームであり、追加的に準同型です。
2つの暗号文の加算のみをサポートし、それらの間の乗算はサポートしません。また、平文番号を暗号文に追加または乗算することもできます。
この例ではpython-paillier
、Paillier暗号システムを使用した部分準同型暗号化用のPythonライブラリを使用します。
from phe import paillier
num1 = 10
num2 = 20
pub_key, priv_key = paillier.generate_paillier_keypair()
cipher_num1, cipher_num2 = pub_key.encrypt(num1), pub_key.encrypt(num2)
# add two encrypted numbers together
result = cipher_num1 + cipher_num2
result = priv_key.decrypt(result)
print("add two encrypted numbers together:",result)
# add an encrypted number to a plaintext number
result = cipher_num1 + 5
result = priv_key.decrypt(result)
print("add an encrypted number to a number:",result)
# multiply an encrypted number by a plaintext number
result = cipher_num1 * 10
result = priv_key.decrypt(result)
print("multiply an encrypted number to a number:",result)
上記の例では、公開鍵と秘密鍵の鍵ペアを生成しました。次に、公開鍵と公開鍵の両方を暗号化num1
しnum2
、それらの暗号文に対して操作を実行しました。
まず、2つの暗号を追加しました。その後、を取り、cipher_num1
それに平文番号を追加しました。最後に、以前と同じプロセスを実行しましたが、今回は加算する代わりにcipher_num1
、平文の数値を掛けました。
これらの操作の計算は、データが暗号化されている間に行われます。また、秘密鍵を使用して結果を復号化することにより、結果の整合性を毎回検証できます。
準同型暗号化(HE)は、データのプライバシーと保護に関しては夢のように見えます。ただし、パフォーマンスが低く、コストが高いため、商用/本番アプリケーションには使用できません。
しかし、最近は速度の面で多くの改善がありました。現在のペースで、今後数年間で世界中に適応されると思います。
出典:https ://www.freecodecamp.org/news/introduction-to-homomorphic-encryption/
1651031842
Dans cet article, nous discuterons du chiffrement homomorphe, du problème qu'il résout et des différents types qui existent.
Ensuite, nous écrirons du code en Python pour montrer certaines de ses capacités en action.
Le nom homomorphe vient du terme algébrique homomorphisme.
"L'homomorphisme est une carte préservant la structure entre deux structures algébriques du même type (telles que deux groupes, deux anneaux ou deux espaces vectoriels)." (Source : Wikipédia )
Homomorphic Encryption
est une forme de chiffrement qui permet aux utilisateurs d'effectuer des opérations binaires sur des données chiffrées sans jamais déchiffrer les données.
Cette forme de cryptage permet de crypter les informations et de les externaliser vers des services/environnements cloud pour le traitement, sans accéder aux données brutes.
Dans le monde d'aujourd'hui, si nous voulons effectuer des calculs sur des données cryptées telles que des opérations mathématiques, nous devons d'abord les décrypter. Ensuite, nous devons faire nos calculs, et enfin chiffrer à nouveau les données afin de les renvoyer.
Mais que se passe-t-il lorsque les données cryptées sont très sensibles et que nous ne voulons pas que d'autres services y aient accès ? C'est ici Homomorphic encryption
qu'entre en jeu.
Un exemple plus pratique serait un système/service qui traite des informations médicales afin de diagnostiquer si un patient a une condition ou non.
Les données que nous partagerions incluent probablement des informations très sensibles sur les antécédents médicaux du patient. C'est donc quelque chose que nous voulons nous assurer qu'il ne sera accessible à personne d'autre.
À l' aide Homomorphic Encryption
de , le système/service peut traiter les calculs requis sur les données cryptées, renvoyant le résultat du diagnostic sans savoir quelles informations sont traitées.
Le partage d'informations sensibles via différentes plates-formes trahit notre vie privée. D'autre part, le fait de pouvoir modifier et effectuer des opérations sur les données alors qu'elles sont cryptées garantit la confidentialité des données.
L'objectif du chiffrement homomorphe est le suivant : étant donné toute entrée telle queinput := Enc(x1),...,Enc(xn)
, pour toute fonction arbitraire f
qui applique un nombre infini d'additions ou de multiplications telles que value := f(Enc(x1),...,Enc(xn))
, la valeur peut être calculée pendant que l'entrée est chiffrée.
Les opérations arithmétiques, en fin de compte, sont implémentées au niveau matériel (comme toute autre chose) sous des circuits arithmétiques ou booléens.
Les opérations que nous voulons effectuer sont l'addition homomorphe et la multiplication homomorphe. Les noms Addition et Multiplication sont donnés en raison du comportement similaire de l'addition binaire et de la multiplication binaire que les portes logiques XOR et AND ont en conséquence. La combinaison de ces deux portes peut représenter n'importe quelle fonction booléenne.
Les facteurs font varier la complexité en fonction du nombre et du type d'opérations.
En raison de ces restrictions et du problème de la construction d'un algorithme de chiffrement entièrement homomorphe (supportant à la fois l'addition homomorphe et la multiplication homomorphe), différents schémas ont été mis en œuvre au fil du temps.
Les types de cryptage homomorphe les plus courants sont :
Le chiffrement homomorphe partiel (PHE) permet d'effectuer une seule opération sur le texte chiffré un nombre infini de fois. Cette opération peut être uniquement une addition ou uniquement une multiplication.
Les algorithmes de chiffrement partiellement homomorphe sont plus faciles à concevoir et sont très utiles dans les applications qui utilisent une opération arithmétique.
Le chiffrement quelque peu homomorphe (SHE) permet d'effectuer à la fois l'addition et la multiplication, mais pour un nombre limité de fois. Cette limitation est évaluée jusqu'à une certaine profondeur dans la logique du circuit. Il s'agit d'une étape très importante pour atteindre le chiffrement entièrement homomorphe.
Le cryptage entièrement homomorphe (FHE) permet d'effectuer à la fois l'addition et la multiplication sur le texte chiffré un nombre infini de fois, prenant en charge des calculs arbitraires sur des données cryptées.
Le problème majeur avec le cryptage entièrement homomorphe est la rentabilité à la fois en termes de vitesse et d'exigences de stockage par rapport aux opérations en clair.
Le cryptosystème Paillier a été inventé par Pascal Paillier en 1999. Il s'agit d'un schéma de chiffrement homomorphe partiel (PHE) et homomorphe additif.
Il ne prend en charge que l'addition de deux textes chiffrés et non la multiplication entre eux. En outre, un nombre en clair peut être ajouté ou multiplié au texte chiffré.
Dans cet exemple, nous utilisons python-paillier
, une bibliothèque Python pour le chiffrement partiellement homomorphe utilisant le système de chiffrement Paillier.
from phe import paillier
num1 = 10
num2 = 20
pub_key, priv_key = paillier.generate_paillier_keypair()
cipher_num1, cipher_num2 = pub_key.encrypt(num1), pub_key.encrypt(num2)
# add two encrypted numbers together
result = cipher_num1 + cipher_num2
result = priv_key.decrypt(result)
print("add two encrypted numbers together:",result)
# add an encrypted number to a plaintext number
result = cipher_num1 + 5
result = priv_key.decrypt(result)
print("add an encrypted number to a number:",result)
# multiply an encrypted number by a plaintext number
result = cipher_num1 * 10
result = priv_key.decrypt(result)
print("multiply an encrypted number to a number:",result)
Dans l'exemple ci-dessus, nous avons généré une paire de clés composée d'une clé publique et d'une clé privée. Ensuite, nous avons chiffré à la fois num1
et num2
avec la clé publique et effectué des opérations sur leurs textes chiffrés.
Tout d'abord, nous avons ajouté les deux chiffres. Après cela, nous avons pris le cipher_num1
et y avons ajouté un numéro en clair. Enfin, nous avons suivi le même processus qu'auparavant, mais au lieu d'additionner, nous avons cipher_num1
cette fois multiplié le par un nombre en clair.
Le calcul de ces opérations a lieu pendant que les données sont cryptées. De plus, nous pouvons vérifier l'intégrité du résultat à chaque fois en le déchiffrant à l'aide de la clé privée.
Le cryptage homomorphe (HE) ressemble à un rêve en matière de confidentialité et de protection des données. Mais ses performances médiocres et ses coûts élevés l'empêchent toujours d'être utilisé dans des applications commerciales/de production.
Mais il y a eu de nombreuses améliorations en termes de vitesse ces derniers temps. Au rythme actuel, je pense qu'il sera adapté dans le monde entier au cours des prochaines années.
Link: https://www.freecodecamp.org/news/introduction-to-homomorphic-encryption/
1650335400
php-encryption
composer require defuse/php-encryption
This is a library for encrypting data with a key or password in PHP. It requires PHP 5.6 or newer and OpenSSL 1.0.1 or newer. We recommend using a version of PHP that still has security support, which at the time of writing means PHP 7.3 or later. Using this library with an unsupported version of PHP could lead to security vulnerabilities.
The current version of php-encryption
is v2.3.1. This library is expected to remain stable and supported by its authors with security and bugfixes until at least January 1st, 2024.
The library is a joint effort between Taylor Hornby and Scott Arciszewski as well as numerous open-source contributors.
What separates this library from other PHP encryption libraries is, firstly, that it is secure. The authors used to encounter insecure PHP encryption code on a daily basis, so they created this library to bring more security to the ecosystem. Secondly, this library is "difficult to misuse." Like libsodium, its API is designed to be easy to use in a secure way and hard to use in an insecure way.
This library requires no special dependencies except for PHP 5.6 or newer with the OpenSSL extensions (version 1.0.1 or later) enabled (this is the default). It uses random_compat, which is bundled in with this library so that your users will not need to follow any special installation steps.
Start with the Tutorial. You can find instructions for obtaining this library's code securely in the Installing and Verifying documentation.
After you've read the tutorial and got the code, refer to the formal documentation for each of the classes this library provides:
If you encounter difficulties, see the FAQ answers. The fixes to the most commonly-reported problems are explained there.
If you're a cryptographer and want to understand the nitty-gritty details of how this library works, look at the Cryptography Details documentation.
If you're interested in contributing to this library, see the Internal Developer Documentation.
This library is intended for server-side PHP software that needs to encrypt data at rest. If you are building software that needs to encrypt client-side, or building a system that requires cross-platform encryption/decryption support, we strongly recommend using libsodium instead.
If the documentation is not enough for you to understand how to use this library, then you can look at an example project that uses this library:
This code has not been subjected to a formal, paid, security audit. However, it has received lots of review from members of the PHP security community, and the authors are experienced with cryptography. In all likelihood, you are safer using this library than almost any other encryption library for PHP.
If you use this library as a part of your business and would like to help fund a formal audit, please contact Taylor Hornby.
The GnuPG public key used to sign current and older releases is available in dist/signingkey.asc. Its fingerprint is:
2FA6 1D8D 99B9 2658 6BAC 3D53 385E E055 A129 1538
You can verify it against Taylor Hornby's contact page and twitter.
Due to the old key expiring, new releases will be signed with a new public key available in dist/signingkey-new.asc. Its fingerprint is:
6DD6 E677 0281 5846 FC85 25A3 DD2E 507F 7BDB 1669
A signature of this new key by the old key is available in dist/signingkey-new.asc.sig.
Author: defuse
Source Code: https://github.com/defuse/php-encryption
License: MIT License
1646532780
jose-simple
Proper encryption ought to be simple, and widespread.
Jose-Simple simplifies the encryption and decryption of data using the JOSE (JSON Object Signing and Encryption) standard.
node-jose
by Cisco.node-jose
does not allow you to use private keys with passwords, and they have no intention of changing that.npm install jose-simple
const jose = require('jose-simple')
// You need a private / public JWE key pair.
// Either load them from `.pem` files, create them, or somehow acquire them.
// The private key must not have a passphrase or cypher!
// see https://github.com/cisco/node-jose/issues/69#issuecomment-236133179
// see also https://github.com/cisco/node-jose/issues/234#issuecomment-457615794
// see unit tests for a simple example.
const { encrypt, decrypt } = jose(privateKey, publicKey)
const someData = {
some: 'amazing data',
you: 'want to keep hidden',
from: 'prying eyes'
}
encrypt(someData).then(encrypted => {
console.log('encrypted', encrypted)
decrypt(encrypted).then(decrypted => {
console.log('decrypted', decrypted)
// decrypted will be the same as someData
})
})
You can add encrypt
options as follows:
const { encrypt, decrypt } = jose(privateKey, publicKey, {
format: 'compact'
protect: true,
// or any of the encrypt options than can be passed to JWE.createEncrypt.
// https://github.com/cisco/node-jose/blob/master/lib/jwe/encrypt.js#L660-L668
})
Branch | Status | Coverage | Audit | Comment |
---|---|---|---|---|
develop | Work in progress | |||
main | Latest release |
npm test
— runs the unit tests. The tests give an example of how to create key pairs too. (Leverages the crypto.generateKeyPair
libraries introduced in Node 10.12.0
.)npm run test:unit:cov
— runs the unit tests with code coveragenpm run lint
Contributions are welcome. Please see CONTRIBUTING for more details.
Author: Davesag
Source Code: https://github.com/davesag/jose-simple
License:
1646532644
secp256k1Cipher
Encrypt and decrypt data use secp256k1
Run this command:
With Dart:
$ dart pub add secp256k1cipher
With Flutter:
$ flutter pub add secp256k1cipher
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get
):
dependencies:
secp256k1cipher: ^0.2.7
Alternatively, your editor might support dart pub get
or flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:secp256k1cipher/secp256k1cipher.dart';
import 'package:secp256k1cipher/secp256k1cipher.dart';
void main(){
var alic = generateKeyPair(); // Create Alic keypair
var bob = generateKeyPair(); // Create Bob keypair
var raw_str = 'Encrypt and decrypt data use secp256k1'; // This is what alic want to say to bob
var enc_map = pubkeyEncrypt(strinifyPrivateKey(alic.privateKey), strinifyPublicKey(bob.publicKey), raw_str); // use alic's privatekey and bob's publickey means alic say to bob
var enc_str = enc_map['enc']; // Get encrypted base64 string
var iv = enc_map['iv']; // Get random IV
// next thing, you can send enc_str and IV via internet to bob
var decryptd = privateDecrypt(strinifyPrivateKey(bob.privateKey), strinifyPublicKey(alic.publicKey), enc_str, iv); // use bob's privatekey and alic's publickey means bob can read message from alic
print('alic say:${decryptd}');
}
Download Details:
Author: ipconfiger
Source Code: https://github.com/ipconfiger/secp256k1Cipher
1644694800
Simple interface for ElGamal and Homomorphic-ElGamal cryptosystems.
use curv::arithmetic::traits::Modulo;
use curv::arithmetic::traits::Samplable;
use curv::BigInt;
use elgamal::{
rfc7919_groups::SupportedGroups, ElGamal, ElGamalKeyPair, ElGamalPP, ElGamalPrivateKey,
ElGamalPublicKey,ExponentElGamal,ElGamalCiphertext,
};
fn main() {
// choose suitable field parameter, https://tools.ietf.org/html/rfc7919
let group_id = SupportedGroups::FFDHE2048;
let alice_pp = ElGamalPP::generate_from_rfc7919(group_id);
// create a public, secret keypair
let alice_key_pair = ElGamalKeyPair::generate(&alice_pp);
// basic en/decryption roundtrip
let message = BigInt::from(13);
let cipher = ElGamal::encrypt(&message, &alice_key_pair.pk).unwrap();
let message_tag = ElGamal::decrypt(&cipher, &alice_key_pair.sk).unwrap();
println!("basic encryption: message: {}, decrypted: {}", message, message_tag);
// homomorphic multiplication
let factor_1 = BigInt::from(13);
let factor_2 = BigInt::from(9);
let cipher = ElGamal::encrypt(&factor_1, &alice_key_pair.pk).unwrap();
let constant_cipher = ElGamal::encrypt(&factor_2, &alice_key_pair.pk).unwrap();
// homomorphic multiplication in cipher space
let product_cipher = ElGamal::mul(&cipher, &constant_cipher).unwrap();
// decrypt homomorphic product
let product_tag = ElGamal::decrypt(&product_cipher, &alice_key_pair.sk).unwrap();
println!(" factor1: {} * factor 2: {} = {}; decrypted homomorphic product: {}", factor_1, factor_2, &factor_1 * &factor_2, product_tag);
// homomorphic (pow) addition
// note to self: we now have (g^r, g^m * h^r) instead of (g^r, m * h^r)
// data set:
let data = vec![BigInt::from(1),BigInt::from(10), BigInt::from(100)];
let randomness = vec![BigInt::sample_below(&alice_pp.q), BigInt::sample_below(&alice_pp.q), BigInt::sample_below(&alice_pp.q)];
// encrypt each data point
let mut ciphers: Vec<ElGamalCiphertext> = Vec::new();
for (idx, number) in data.iter().enumerate() {
let c = ExponentElGamal::encrypt_from_predefined_randomness(&number, &alice_key_pair.pk, &randomness[idx]).unwrap();
ciphers.push(c);
}
// finally, we add the data
let n = ciphers.len();
let mut addition_cipher: ElGamalCiphertext = ExponentElGamal::add(&ciphers[0], &ciphers[1]).unwrap();
for idx in 2..n {
addition_cipher = ExponentElGamal::add(&ciphers[idx], &addition_cipher).unwrap();
}
// and now we decrypt and due to the exponentiation we end up with g^m
let c_tag = ExponentElGamal::decrypt_exp(&addition_cipher, &alice_key_pair.sk).unwrap();
// and we're super inefficiently brute-forcing g^i mod p to validate the raw sum
for i in 0..1_000_000 {
let res = BigInt::mod_pow(&alice_key_pair.pk.pp.g, &BigInt::from(i), &alice_key_pair.pk.pp.p);
if res.eq(&c_tag) {
println!("result: {}", i);
break;
}
}
}
Several tests are included:
cargo test --lib
Please note that the test for generate_safe
is not part of the default test run due to the potentially long runtime. To run the expensive tests:
cargo test --lib -- --ignored
Benchmarks are also included:
cargo bench
The benchmarks are created bycriterion.rs and the default reports include pretty cool plots, which are best with gnuplot
installed, e.g., brew install gnuplot
. The benchmark reports can found in ../target/criterion/report
and open index.html
should do.
To run the benches without plots, or with any of the other criterion.rs options, use
cargo bench --bench elgamal_benches -- --noplot
See benches/examples
for a full results set.
Feel free to reach out or join ZenGo X Telegram for discussions on code and research.
Download Details:
Author: ZenGo-X
Source Code: https://github.com/ZenGo-X/rust-elgamal
License: GPL-3.0 License
1642849613
encryptions
A plugin for using native AES /Argon2 algorithms in Android/IOS. Since it's not possible to run automatic test for flutter plugins currently as far as I know, a few test cases are provided along with the example:
Tested platforms:
Supported algorithms:
NoPadding
then you need to make sure the size of the block you're going to encrypt must be multiple of 16(which is the AES block size).Uint8List key256 = hex
.decode("163928fb9615edf6005afc98d9fdbb3d830b3a286ebef64dd70be848f17bf9cc");
Uint8List iv = hex.decode("c1f6fd873e14050697c168b3e9da5db2");
Uint8List plain = hex.decode("01040000000300000002400000008b2e");
AES aes = AES.ofCBC(key256, iv, PaddingScheme.PKCS5Padding);
Uint8List encrypted = await aes.encrypt(plain);
Uint8List decrypted = await aes.decrypt(encrypted);
Uint8List password = utf8.encode("password");
Uint8List salt = utf8.encode("helloworld");
Argon2 argon2 = Argon2(iterations: 16, hashLength: 64, memory: 256, parallelism: 2);
Uint8List hash = await argon2.argon2i(password, salt);
for more details, try to have a look at example/lib/test_case.dart
Run this command:
With Flutter:
$ flutter pub add encryptions
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
encryptions: ^1.1.0+1
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:encryptions/encryptions.dart';
import 'package:encryptions_example/test_case.dart';
import 'package:encryptions_example/test_case_config.dart';
import 'package:flutter/material.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<List<Report>> reports;
@override
void initState() {
super.initState();
reports = test();
}
static const successStyle = TextStyle(fontSize: 16, color: Colors.green);
static const errorStyle = TextStyle(fontSize: 16, color: Colors.red);
static const padding = EdgeInsets.all(5.0);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Padding(
padding: const EdgeInsets.only(top: 20.0, left: 5, right: 5),
child: _renderReport(),
),
),
);
}
Widget _renderTable(List<TableRow> rows) {
return SingleChildScrollView(
child: Table(
border: new TableBorder.all(width: 1.0, color: Colors.grey),
children: rows,
),
);
}
TableRow _createRow(Report report) {
return TableRow(key: ObjectKey(report.name), children: <Widget>[
TableCell(
child: Padding(
padding: padding,
child: Text(
"${report.name}",
style: report.success ? successStyle : errorStyle,
),
),
),
]);
}
Widget _renderReport() {
return FutureBuilder<List<Report>>(
future: reports,
builder: (_, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
if (snapshot.hasError) {
print('got error! ${snapshot.error}');
return Text("Error:${snapshot.error}");
}
print("Done! ${snapshot.data}");
return _renderTable(snapshot.data.map((report) => _createRow(report)).toList());
default:
return Center(
child: Text("Testing..."),
);
}
},
);
}
Future<List<Report>> test() async {
List<Report> reports = [];
for (int i = 0; i < testCases.length; i++) {
TestCase t = testCases[i];
bool success;
try {
success = await t.execute();
} catch (err, stack) {
print(err);
print(stack);
success = false;
}
reports.add(Report(t.name, success));
}
return reports;
}
}
Download Details:
Author: drriguz
Source Code: https://github.com/drriguz/encryptions
1638255904
In this video, you will learn the basics of encryption, types of encryption, how does encryption work, a few popular encryption algorithms and protocols, and brute force attack. Encryption allows data and text to be in the form of encrypted algorithms and is then placed on a storage cloud. This can ensure the protection of data. Even if the information is stored at the third-party provider, one can access the data safely with the help of encryption and decryption keys.
00:00:00 Introduction
00:01:07 Agenda
00:01:57 Prerequisites
00:05:14 What is Cryptography?
00:06:35 What is Encryption?
00:10:42 Cryptography Vs Encryption
00:11:25 How does Encryption work?
00:13:04 What is Decryption?
00:14:13 Encryption Vs Decryption
00:15:25 Types of Encryption
00:18:21 Encryption Algorithms and Protocols
00:33:22 What is Brute force attack?
00:34:29 Summary
#encryption #cryptography #security
1636246980
One of the reasons WordPress is so popular is because it's simple, easy to use, and flexible. In this guide, you will learn how to install WordPress CMS on the Rocky Linux 8.4. You will be installing WordPress under the LAMP Stack .