Как зашифровать/расшифровать данные на golang/javascript передаваемые по websocket протоколу?

Пользователь

от aniyah , в категории: Общие вопросы , 7 месяцев назад

Как зашифровать/расшифровать данные на golang/javascript передаваемые по websocket протоколу?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp Pocket

1 ответ

Пользователь

от domenick , 7 месяцев назад

@aniyah 

Чтобы зашифровать и расшифровать данные, передаваемые по протоколу WebSocket в Go и JavaScript, вы можете использовать алгоритмы шифрования, такие как AES (Advanced Encryption Standard) или RSA (Rivest-Shamir-Adleman).


Ниже приведен пример реализации шифрования/расшифрования данных с использованием алгоритма AES на Go:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
)

func encrypt(data []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	nonce := make([]byte, 12)
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, err
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	ciphertext := aesgcm.Seal(nil, nonce, data, nil)
	ciphertext = append(nonce, ciphertext...)

	return ciphertext, nil
}

func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	nonceSize := aesgcm.NonceSize()
	nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]

	plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return nil, err
	}

	return plaintext, nil
}

func main() {
	key := []byte("my-32-byte-key1234567890123456")

	plaintext := []byte("Hello, World!")

	ciphertext, err := encrypt(plaintext, key)
	if err != nil {
		panic(err)
	}

	fmt.Println("Encrypted:", base64.StdEncoding.EncodeToString(ciphertext))

	decrypted, err := decrypt(ciphertext, key)
	if err != nil {
		panic(err)
	}

	fmt.Println("Decrypted:", string(decrypted))
}


Алгоритм AES использует ключ длиной 32 байта. Обратите внимание, что nonce (случайное число, используемое для каждого шифрования) также добавляется к зашифрованному тексту.


На JavaScript вы можете использовать библиотеки, такие как crypto-js или node-forge, для реализации шифрования/расшифрования AES.


Ниже приведен пример использования crypto-js в JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const cryptoJs = require('crypto-js');

const key = cryptoJs.enc.Utf8.parse('my-32-byte-key1234567890123456');
const plaintext = 'Hello, World!';

const ciphertext = cryptoJs.AES.encrypt(plaintext, key, {
  mode: cryptoJs.mode.ECB,
}).toString();

console.log('Encrypted:', ciphertext);

const decrypted = cryptoJs.AES.decrypt(ciphertext, key, {
  mode: cryptoJs.mode.ECB,
}).toString(cryptoJs.enc.Utf8);

console.log('Decrypted:', decrypted);


Обратите внимание, что использование режима ECB (Electronic Codebook) в данном примере не является наиболее безопасной практикой. Рекомендуется использовать режимы шифрования, такие как CBC (Cipher Block Chaining) или GCM (Galois/Counter Mode), для обеспечения более высокого уровня безопасности.