Blockchain и шифрование: различия между версиями

Материал из Artem Aleksashkin's Wiki
Перейти к навигации Перейти к поиску
Строка 320: Строка 320:
echo ${KEY_PASSWORD} > ${NAME}.pass
echo ${KEY_PASSWORD} > ${NAME}.pass
openssl x509 -in ${NAME}.crt -text -noout
openssl x509 -in ${NAME}.crt -text -noout
openssl rsa -passin pass:`cat ./${NAME}.pass` -in ${NAME}.key -out ${NAME}.wo.pwd.key


# add to Ubuntu
# add to Ubuntu

Версия от 02:19, 26 января 2019

Генерация случайных строк

#!/bin/bash
# bash generate random alphanumeric string
#

# bash generate random 32 character alphanumeric string (upper and lowercase) and 
NEW_UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)

# bash generate random 32 character alphanumeric string (lowercase only)
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1

# Random numbers in a range, more randomly distributed than $RANDOM which is not
# very random in terms of distribution of numbers.

# bash generate random number between 0 and 9
cat /dev/urandom | tr -dc '0-9' | fold -w 256 | head -n 1 | head --bytes 1

# bash generate random number between 0 and 99
NUMBER=$(cat /dev/urandom | tr -dc '0-9' | fold -w 256 | head -n 1 | sed -e 's/^0*//' | head --bytes 2)
if [ "$NUMBER" == "" ]; then
  NUMBER=0
fi

# bash generate random number between 0 and 999
NUMBER=$(cat /dev/urandom | tr -dc '0-9' | fold -w 256 | head -n 1 | sed -e 's/^0*//' | head --bytes 3)
if [ "$NUMBER" == "" ]; then
  NUMBER=0
fi

Ассиметричное шифрование

Есть 2 ключа. Публичный и приватный.

Концепция делится на 2 части:

  • Концепция "достоверность отправителя". Вы подписываете сообщение приватным ключом. Остальные могут убедится, что сообщение написали вы, т.к. подпись проверяется открытым ключом.
  • Концепция "почтовый ящик". Вы шифруете сообщение публичным ключом. Расшифровать можно только приватным. Отправляете сообщение в мир, а открыть его может только тот у кого есть ключ.

В конечном итоге вы шифруете открытым ключом получателя и подписываете своим ключом. Получается что получатель может убедится, что отправили его именно вы, а расшифровать может только он.

Концепция "достоверность отправителя"

#!/usr/bin/env bash

NAME=alice
PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
openssl genrsa -aes256 -passout pass:${PASSWORD} -out ${NAME}.private.pem 8912
openssl rsa -in ${NAME}.private.pem -passin pass:${PASSWORD} -pubout -out ${NAME}.public.pem
echo $PASSWORD > ${NAME}.pass

NAME=bob
PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
openssl genrsa -aes256 -passout pass:${PASSWORD} -out ${NAME}.private.pem 8912
openssl rsa -in ${NAME}.private.pem -passin pass:${PASSWORD} -pubout -out ${NAME}.public.pem
echo $PASSWORD > ${NAME}.pass

I=0

I=$((I+1))
NAME=alice
FILE=`printf "%03d" ${I}`.${NAME}.msg
MESSAGE='Hello Bob! I love you'
PASSWORD=`cat ${NAME}.pass`
echo ${MESSAGE} > ${FILE}
openssl dgst -sha256 -sign ${NAME}.private.pem -passin pass:${PASSWORD} -out ${FILE}.sign.sha256 ${FILE}
openssl base64 -in ${FILE}.sign.sha256 -out ${FILE}.sign.sha256.base64

I=$((I+1))
NAME=bob
FILE=`printf "%03d" ${I}`.${NAME}.msg
MESSAGE='Hello Alice! I love you tooo :*'
PASSWORD=`cat ${NAME}.pass`
echo ${MESSAGE} > ${FILE}
openssl dgst -sha256 -sign ${NAME}.private.pem -passin pass:${PASSWORD} -out ${FILE}.sign.sha256 ${FILE}
openssl base64 -in ${FILE}.sign.sha256 -out ${FILE}.sign.sha256.base64

for FILE in `ls -1 *.msg`
do
	NAME=`echo ${FILE} | awk -F\. '{print $2}'`
	openssl base64 -d -in ${FILE}.sign.sha256.base64 -out ${FILE}.sign.sha256.check
	openssl dgst -sha256 -verify ${NAME}.public.pem -signature ${FILE}.sign.sha256.check ${FILE}
done

Концепция "почтовый ящик"

#!/usr/bin/env bash

NAME=alice
PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
openssl genrsa -aes256 -passout pass:${PASSWORD} -out ${NAME}.private.pem 8912
openssl rsa -in ${NAME}.private.pem -passin pass:${PASSWORD} -pubout -out ${NAME}.public.pem
echo $PASSWORD > ${NAME}.pass

NAME=bob
PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
openssl genrsa -aes256 -passout pass:${PASSWORD} -out ${NAME}.private.pem 8912
openssl rsa -in ${NAME}.private.pem -passin pass:${PASSWORD} -pubout -out ${NAME}.public.pem
echo $PASSWORD > ${NAME}.pass

I=0

I=$((I+1))
NAME=bob
FILE=`printf "%03d" ${I}`.${NAME}.msgenc
MESSAGE='Hello Bob! I love you'
echo ${MESSAGE} > ${FILE}
openssl rsautl -encrypt -pubin -inkey ${NAME}.public.pem -in ${FILE} -out ${FILE}.encrypted

I=$((I+1))
NAME=alice
FILE=`printf "%03d" ${I}`.${NAME}.msgenc
MESSAGE='Hello Alice! I love you tooo :*'
echo ${MESSAGE} > ${FILE}
openssl rsautl -encrypt -pubin -inkey ${NAME}.public.pem -in ${FILE} -out ${FILE}.encrypted

for FILE in `ls -1 *.msgenc`
do
	NAME=`echo ${FILE} | awk -F\. '{print $2}'`
	PASSWORD=`cat ${NAME}.pass`
	openssl rsautl -decrypt -inkey ${NAME}.private.pem -passin pass:${PASSWORD} -in ${FILE}.encrypted -out ${FILE}.encrypted.check
	CHECK=`diff ${FILE} ${FILE}.encrypted.check`
	if [ -z "$CHECK" ]
	then
	      echo "VERIFY OK"
	fi
done

Зашифрованные сообщения с подписью

#!/usr/bin/env bash

NAME=alice
PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
openssl genrsa -aes256 -passout pass:${PASSWORD} -out ${NAME}.private.pem 8912
openssl rsa -in ${NAME}.private.pem -passin pass:${PASSWORD} -pubout -out ${NAME}.public.pem
echo $PASSWORD > ${NAME}.pass

NAME=bob
PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
openssl genrsa -aes256 -passout pass:${PASSWORD} -out ${NAME}.private.pem 8912
openssl rsa -in ${NAME}.private.pem -passin pass:${PASSWORD} -pubout -out ${NAME}.public.pem
echo $PASSWORD > ${NAME}.pass

I=0

I=$((I+1))
FROM=alice
TO=bob
FILE=msg.`printf "%03d" ${I}`.${FROM}.${TO}
PASSWORD=`cat ${FROM}.pass`
MESSAGE='Hello Bob! I love you'
echo ${MESSAGE} > ${FILE}
openssl rsautl -encrypt -pubin -inkey ${TO}.public.pem -in ${FILE} -out ${FILE}.encrypted
openssl dgst -sha256 -sign ${FROM}.private.pem -passin pass:${PASSWORD} -out sign.${FILE}.encrypted ${FILE}.encrypted
openssl base64 -in ${FILE}.encrypted -out ${FILE}.encrypted.base64
openssl base64 -in sign.${FILE}.encrypted -out sign.${FILE}.encrypted.base64
rm ${FILE} ${FILE}.encrypted sign.${FILE}.encrypted

I=$((I+1))
FROM=bob
TO=alice
FILE=msg.`printf "%03d" ${I}`.${FROM}.${TO}
PASSWORD=`cat ${FROM}.pass`
MESSAGE='Hello Alice! I love you tooo :*'
echo ${MESSAGE} > ${FILE}
openssl rsautl -encrypt -pubin -inkey ${TO}.public.pem -in ${FILE} -out ${FILE}.encrypted
openssl dgst -sha256 -sign ${FROM}.private.pem -passin pass:${PASSWORD} -out sign.${FILE}.encrypted ${FILE}.encrypted
openssl base64 -in ${FILE}.encrypted -out ${FILE}.encrypted.base64
openssl base64 -in sign.${FILE}.encrypted -out sign.${FILE}.encrypted.base64
rm ${FILE} ${FILE}.encrypted sign.${FILE}.encrypted

for FILE in `ls -1 msg.*`
do
	FROM=`echo ${FILE} | awk -F\. '{print $3}'`
	TO=`echo ${FILE} | awk -F\. '{print $4}'`
	PASSWORD=`cat ${TO}.pass`
	echo '====================================='
	echo 'FROM '${FROM}
	echo 'TO '${TO}
	openssl base64 -d -in ${FILE} -out ${FILE}.binary
	openssl base64 -d -in sign.${FILE} -out sign.${FILE}.binary
	openssl dgst -sha256 -verify ${FROM}.public.pem -signature sign.${FILE}.binary ${FILE}.binary
	openssl rsautl -decrypt -inkey ${TO}.private.pem -passin pass:${PASSWORD} -in ${FILE}.binary -out ${FILE}.binary.dencrypted
	cat ${FILE}.binary.dencrypted
	echo '====================================='
	rm ${FILE}.binary sign.${FILE}.binary ${FILE}.binary.dencrypted
done

Хэширование

Хэширование - это получение контрольной суммы от данных. Длина хэша ограничена. Длина данных - нет.

Коллизия - это когда на 2 пары разных данных получается один и тот же хэш.

Стойкость к коллизиям, непредсказуемость хэша и равномерная респределенность - главные критерии качества алгоритма хэширования.

Цепочка хэшей - это когда в каждое последующее звено цепи вы добавляете хэш предыдущего звена.

#!/usr/bin/env bash

mkdir users

USERS=(alice bob tom john michael jane mackenzie leo alex jim)
for NAME in ${USERS[*]}
do
	mkdir users/${NAME}
	PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
	openssl genrsa -aes256 -passout pass:${PASSWORD} -out users/${NAME}/private.pem 4096
	openssl rsa -in users/${NAME}/private.pem -passin pass:${PASSWORD} -pubout -out users/${NAME}/public.pem
	echo $PASSWORD > users/${NAME}/pass
done

mkdir transactions
I=0
while [ $I -le 1000 ]
do
	FROM=${USERS[$RANDOM % ${#USERS[@]}]}
	TO=${USERS[$RANDOM % ${#USERS[@]}]}
	if [ "$FROM" == "$TO" ]
	then
	continue
	fi
	I=$((I+1))
	FILE=transaction.`printf "%03d" ${I}`.${FROM}.${TO}
	MESSAGE=$((RANDOM % 100 + 1))
	echo ${MESSAGE} > transactions/${FILE}
	openssl dgst -sha256 -sign users/${FROM}/private.pem -passin pass:`cat users/${FROM}/pass` -out transactions/sign.${FILE} transactions/${FILE}
	openssl base64 -in transactions/sign.${FILE} -out transactions/sign.${FILE}.base64
	rm transactions/sign.${FILE}
done

I=0
ls -1 transactions/transaction.* | while read f
do
	I=$((I+1))
	FILE=`basename ${f}`
	FROM=`echo ${FILE} | awk -F\. '{print $3}'`
	TO=`echo ${FILE} | awk -F\. '{print $4}'`
	openssl base64 -d -in transactions/sign.${FILE}.base64 -out transactions/sign.${FILE}.base64.binary
	openssl dgst -sha256 -verify users/${FROM}/public.pem -signature transactions/sign.${FILE}.base64.binary transactions/${FILE}
	if [[ $? -eq 0 ]]
	then
	echo ${FILE}
	echo 'Verification ERROR!'
	break
	fi
	rm transactions/sign.${FILE}.base64.binary
done

Генерация корневого сертификата и дочернего для хоста

#!/usr/bin/env bash

ROOT_NAME="rootCA"
ROOT_KEY_PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
ROOT_CRT_DAYS=10950
ROOT_CRT_EMAIL="email@example.com"
ROOT_CRT_COUNTRY="RU"
ROOT_CRT_STATE="Moscow"
ROOT_CRT_LOCATION="Moscow"
ROOT_CRT_ORGANIZATION="Org"
ROOT_CRT_ORGANIZATION_UNIT="Org"
ROOT_CRT_COMMON_NAME="example.com"

openssl genrsa\
    -des3\
    -passout pass:${ROOT_KEY_PASSWORD}\
    -out ${ROOT_NAME}.key 2048
openssl req\
    -x509\
    -new\
    -key ${ROOT_NAME}.key\
    -passin pass:${ROOT_KEY_PASSWORD}\
    -days ${ROOT_CRT_DAYS}\
    -subj "/emailAddress=${ROOT_CRT_EMAIL}/C=${ROOT_CRT_COUNTRY}/ST=${ROOT_CRT_STATE}/L=${ROOT_CRT_LOCATION}/O=${ROOT_CRT_ORGANIZATION}/OU=${ROOT_CRT_ORGANIZATION_UNIT}/CN=${ROOT_CRT_COMMON_NAME}"\
    -out ${ROOT_NAME}.crt
echo ${ROOT_KEY_PASSWORD} > ${ROOT_NAME}.pass

NAME="example"
KEY_PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
CRT_DAYS=3650
CRT_EMAIL="email@example.com"
CRT_COUNTRY="RU"
CRT_STATE="Moscow"
CRT_LOCATION="Moscow"
CRT_ORGANIZATION="Org"
CRT_ORGANIZATION_UNIT="Org"
CRT_COMMON_NAME="example.com"

openssl genrsa\
    -des3\
    -passout pass:${KEY_PASSWORD}\
    -out ${NAME}.key 2048
openssl req\
    -new\
    -key ${NAME}.key\
    -passin pass:${KEY_PASSWORD}\
    -subj "/emailAddress=${CRT_EMAIL}/C=${CRT_COUNTRY}/ST=${CRT_STATE}/L=${CRT_LOCATION}/O=${CRT_ORGANIZATION}/OU=${CRT_ORGANIZATION_UNIT}/CN=${CRT_COMMON_NAME}"\
    -out ${NAME}.csr
openssl x509\
    -req\
    -in ${NAME}.csr\
    -CA ${ROOT_NAME}.crt\
    -CAkey ${ROOT_NAME}.key\
    -passin pass:${ROOT_KEY_PASSWORD}\
    -CAcreateserial\
    -days ${CRT_DAYS}\
    -extensions v3_req\
    -out ${NAME}.crt\
    -extfile <(cat /etc/ssl/openssl.cnf <(printf "\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @alt_names\n\n[ alt_names ]\nDNS.1 = ${CRT_COMMON_NAME}"))

echo ${KEY_PASSWORD} > ${NAME}.pass
openssl x509 -in ${NAME}.crt -text -noout

openssl rsa -passin pass:`cat ./${NAME}.pass` -in ${NAME}.key -out ${NAME}.wo.pwd.key

# add to Ubuntu

sudo mkdir /usr/share/ca-certificates/extra
sudo cp ${ROOT_NAME}.crt /usr/share/ca-certificates/extra/${ROOT_NAME}.crt
sudo dpkg-reconfigure ca-certificates
sudo update-ca-certificates

Цепочка сертификатов

#!/usr/bin/env bash

ROOT_NAME="rootCA"
ROOT_KEY_PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
ROOT_CRT_DAYS=10950
ROOT_CRT_EMAIL="email@example.com"
ROOT_CRT_COUNTRY="RU"
ROOT_CRT_STATE="Moscow"
ROOT_CRT_LOCATION="Moscow"
ROOT_CRT_ORGANIZATION="Org"
ROOT_CRT_ORGANIZATION_UNIT="Org"
ROOT_CRT_COMMON_NAME="example.com"

openssl genrsa\
    -des3\
    -passout pass:${ROOT_KEY_PASSWORD}\
    -out ${ROOT_NAME}.key 2048
openssl req\
    -x509\
    -new\
    -key ${ROOT_NAME}.key\
    -passin pass:${ROOT_KEY_PASSWORD}\
    -days ${ROOT_CRT_DAYS}\
    -subj "/emailAddress=${ROOT_CRT_EMAIL}/C=${ROOT_CRT_COUNTRY}/ST=${ROOT_CRT_STATE}/L=${ROOT_CRT_LOCATION}/O=${ROOT_CRT_ORGANIZATION}/OU=${ROOT_CRT_ORGANIZATION_UNIT}/CN=${ROOT_CRT_COMMON_NAME}"\
    -out ${ROOT_NAME}.crt
echo ${ROOT_KEY_PASSWORD} > ${ROOT_NAME}.pass

NAME="example"
KEY_PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1`
CRT_DAYS=3650
CRT_EMAIL="email@example.com"
CRT_COUNTRY="RU"
CRT_STATE="Moscow"
CRT_LOCATION="Moscow"
CRT_ORGANIZATION="Org"
CRT_ORGANIZATION_UNIT="Org"
CRT_COMMON_NAME="example.com"

openssl genrsa\
    -des3\
    -passout pass:${KEY_PASSWORD}\
    -out ${NAME}.key 2048
openssl req\
    -new\
    -key ${NAME}.key\
    -passin pass:${KEY_PASSWORD}\
    -subj "/emailAddress=${CRT_EMAIL}/C=${CRT_COUNTRY}/ST=${CRT_STATE}/L=${CRT_LOCATION}/O=${CRT_ORGANIZATION}/OU=${CRT_ORGANIZATION_UNIT}/CN=${CRT_COMMON_NAME}"\
    -out ${NAME}.csr
openssl x509\
    -req\
    -in ${NAME}.csr\
    -CA ${ROOT_NAME}.crt\
    -CAkey ${ROOT_NAME}.key\
    -passin pass:${ROOT_KEY_PASSWORD}\
    -CAcreateserial\
    -days ${CRT_DAYS}\
    -extensions v3_req\
    -out ${NAME}.crt\
    -extfile <(cat /etc/ssl/openssl.cnf <(printf "\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @alt_names\n\n[ alt_names ]\nDNS.1 = ${CRT_COMMON_NAME}"))

echo ${KEY_PASSWORD} > ${NAME}.pass

Ссылки и доп информация