quantum update

This commit is contained in:
number571 2024-10-17 16:32:31 +07:00
parent d2312bac3e
commit 12a6e010f2
61 changed files with 526 additions and 1101 deletions

View File

@ -6,10 +6,15 @@
*??? ??, ????*
### IMPROVEMENTS
- Update `pkg/crypto`: update asymmetric: RSA -> Kyber768/DilithiumM3
### CHANGES
- Update `cmd`: move hidden_lake & secpy_chat to https://github.com/number571/hidden-lake and https://github.com/number571/secpy-chat repositories
- Update `docs`: move hidden_lake docx, pptx, pdf works to https://github.com/number571/hidden-lake repository
- Update `pkg/crypto`: change name of construct functions to abstract names
<!-- ... -->

View File

@ -8,16 +8,18 @@ import (
)
func main() {
keySize := flag.Uint64("size", 2048, "set key size")
flag.Parse()
priv := asymmetric.NewRSAPrivKey(*keySize)
priv := asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
)
if priv == nil {
panic("generate key error")
}
if err := os.WriteFile("priv.key", []byte(priv.ToString()), 0o600); err != nil {
panic(err)
}
if err := os.WriteFile("pub.key", []byte(priv.GetPubKey().ToString()), 0o600); err != nil {
if err := os.WriteFile("pub.key", []byte(priv.GetPubKeyChain().ToString()), 0o600); err != nil {
panic(err)
}
}

View File

@ -4,8 +4,8 @@ import (
"bytes"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/crypto/hashing"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/random"
"github.com/number571/go-peer/pkg/crypto/symmetric"
"github.com/number571/go-peer/pkg/payload/joiner"
@ -22,19 +22,19 @@ var (
// Basic structure describing the user.
type sClient struct {
fSettings message.ISettings
fPrivKeyChain quantum.IPrivKeyChain
fPrivKeyChain asymmetric.IPrivKeyChain
fStructSize uint64
}
// Create client by private key as identification.
// Handle function is used when the network exists.
func NewClient(pSett message.ISettings, pPrivKeyChain quantum.IPrivKeyChain) IClient {
func NewClient(pSett message.ISettings, pPrivKeyChain asymmetric.IPrivKeyChain) IClient {
client := &sClient{
fSettings: pSett,
fPrivKeyChain: pPrivKeyChain,
}
kemPubKey := client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
kemPubKey := client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
encMsg, err := client.encryptWithParams(kemPubKey, []byte{}, 0)
if err != nil {
panic(err)
@ -58,7 +58,7 @@ func (p *sClient) GetMessageLimit() uint64 {
}
// Get private key from client object.
func (p *sClient) GetPrivKeyChain() quantum.IPrivKeyChain {
func (p *sClient) GetPrivKeyChain() asymmetric.IPrivKeyChain {
return p.fPrivKeyChain
}
@ -69,7 +69,7 @@ func (p *sClient) GetSettings() message.ISettings {
// Encrypt message with public key of receiver.
// The message can be decrypted only if private key is known.
func (p *sClient) EncryptMessage(pRecv quantum.IKEMPubKey, pMsg []byte) ([]byte, error) {
func (p *sClient) EncryptMessage(pRecv asymmetric.IKEncPubKey, pMsg []byte) ([]byte, error) {
var (
msgLimitSize = p.GetMessageLimit()
resultSize = uint64(len(pMsg))
@ -83,18 +83,18 @@ func (p *sClient) EncryptMessage(pRecv quantum.IKEMPubKey, pMsg []byte) ([]byte,
}
func (p *sClient) encryptWithParams(
pRecv quantum.IKEMPubKey,
pRecv asymmetric.IKEncPubKey,
pMsg []byte,
pPadd uint64,
) ([]byte, error) {
var (
signer = p.fPrivKeyChain.GetSignerPrivKey()
rand = random.NewCSPRNG()
signer = p.fPrivKeyChain.GetSignPrivKey()
rand = random.NewRandom()
salt = rand.GetBytes(cSaltSize)
)
data := joiner.NewBytesJoiner32([][]byte{pMsg, rand.GetBytes(pPadd)})
hash := hashing.NewHMACSHA256Hasher(salt, bytes.Join(
hash := hashing.NewHMACHasher(salt, bytes.Join(
[][]byte{
signer.GetPubKey().ToBytes(),
pRecv.ToBytes(),
@ -108,7 +108,7 @@ func (p *sClient) encryptWithParams(
return nil, ErrEncryptSymmetricKey
}
cipher := symmetric.NewAESCipher(sk)
cipher := symmetric.NewCipher(sk)
return message.NewMessage(
ct,
cipher.EncryptBytes(joiner.NewBytesJoiner32([][]byte{
@ -123,21 +123,21 @@ func (p *sClient) encryptWithParams(
// Decrypt message with private key of receiver.
// No one else except the sender will be able to decrypt the message.
func (p *sClient) DecryptMessage(pMsg []byte) (quantum.ISignerPubKey, []byte, error) {
func (p *sClient) DecryptMessage(pMsg []byte) (asymmetric.ISignPubKey, []byte, error) {
msg, err := message.LoadMessage(p.fSettings, pMsg)
if err != nil {
return nil, nil, ErrInitCheckMessage
}
// Decrypt session key by private key of receiver.
kemPrivKey := p.fPrivKeyChain.GetKEMPrivKey()
kemPrivKey := p.fPrivKeyChain.GetKEncPrivKey()
skey, err := kemPrivKey.Decapsulate(msg.GetEnck())
if err != nil {
return nil, nil, ErrDecryptCipherKey
}
// Decrypt data block by decrypted session key. Decode data block.
decJoiner := symmetric.NewAESCipher(skey).DecryptBytes(msg.GetEncd())
decJoiner := symmetric.NewCipher(skey).DecryptBytes(msg.GetEncd())
decSlice, err := joiner.LoadBytesJoiner32(decJoiner)
if err != nil || len(decSlice) != 5 {
return nil, nil, ErrDecodeBytesJoiner
@ -153,13 +153,13 @@ func (p *sClient) DecryptMessage(pMsg []byte) (quantum.ISignerPubKey, []byte, er
)
// Load public key and check standart size.
signerPubKey := quantum.LoadSignerPubKey(pkey)
signerPubKey := asymmetric.LoadSignPubKey(pkey)
if signerPubKey == nil { // || pubKey.GetSize() != p.GetPubKey().GetSize()
return nil, nil, ErrDecodePublicKey
}
// Validate received hash with generated hash.
check := hashing.NewHMACSHA256Hasher(salt, bytes.Join(
check := hashing.NewHMACHasher(salt, bytes.Join(
[][]byte{
signerPubKey.ToBytes(),
kemPrivKey.GetPubKey().ToBytes(),

View File

@ -5,7 +5,7 @@ import (
"time"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
testutils "github.com/number571/go-peer/test/utils"
)
@ -25,9 +25,9 @@ PASS
// go test -bench=BenchmarkClient -benchtime=100x -timeout 99999s
func BenchmarkClient(b *testing.B) {
privKeyChain := quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
privKeyChain := asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
)
benchTable := []struct {
@ -38,7 +38,7 @@ func BenchmarkClient(b *testing.B) {
name: "key=768-bit",
client: NewClient(
message.NewSettings(&message.SSettings{
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
FMessageSizeBytes: (8 << 10),
}),
privKeyChain,
@ -62,7 +62,7 @@ func BenchmarkClient(b *testing.B) {
nowEnc := time.Now()
for i := 0; i < b.N; i++ {
encMsg, err := t.client.EncryptMessage(
t.client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
t.client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
randomBytes[i],
)
if err != nil {

View File

@ -6,7 +6,7 @@ import (
"testing"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
)
func TestClient(t *testing.T) {
@ -15,15 +15,15 @@ func TestClient(t *testing.T) {
client := NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: (8 << 10),
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
)
kemPubKey := client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
kemPubKey := client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
msg := []byte("hello, world!")
enc, err := client.EncryptMessage(kemPubKey, msg)
@ -32,13 +32,13 @@ func TestClient(t *testing.T) {
return
}
signerPubKey := client.GetPrivKeyChain().GetSignerPrivKey().GetPubKey()
gotSignerPubKey, dec, err := client.DecryptMessage(enc)
signerPubKey := client.GetPrivKeyChain().GetSignPrivKey().GetPubKey()
gotSignPubKey, dec, err := client.DecryptMessage(enc)
if err != nil {
t.Error(err)
return
}
if !bytes.Equal(signerPubKey.ToBytes(), gotSignerPubKey.ToBytes()) {
if !bytes.Equal(signerPubKey.ToBytes(), gotSignPubKey.ToBytes()) {
t.Error("invalid decrypt signer key")
return
}

View File

@ -32,7 +32,7 @@ func encrypt(client client.IClient, outFilename, inFilename string) error {
}
return err
}
kemPubKey := client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
kemPubKey := client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
chunk, err := client.EncryptMessage(kemPubKey, buf[:n])
if err != nil {
return err

View File

@ -5,7 +5,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
)
func main() {
@ -25,11 +25,11 @@ func newClient() client.IClient {
return client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: (8 << 10),
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
)
}

View File

@ -5,7 +5,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/payload"
)
@ -16,7 +16,7 @@ func main() {
)
msg, err := client1.EncryptMessage(
client2.GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
client2.GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload64(0x0, []byte("hello, world!")).ToBytes(),
)
if err != nil {
@ -37,11 +37,11 @@ func newClient() client.IClient {
return client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: (8 << 10),
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
)
}

View File

@ -2,15 +2,15 @@ package client
import (
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
)
type IClient interface {
GetSettings() message.ISettings
GetMessageLimit() uint64
GetPrivKeyChain() quantum.IPrivKeyChain
GetPrivKeyChain() asymmetric.IPrivKeyChain
EncryptMessage(quantum.IKEMPubKey, []byte) ([]byte, error)
DecryptMessage([]byte) (quantum.ISignerPubKey, []byte, error)
EncryptMessage(asymmetric.IKEncPubKey, []byte) ([]byte, error)
DecryptMessage([]byte) (asymmetric.ISignPubKey, []byte, error)
}

View File

@ -1,261 +0,0 @@
package asymmetric
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"fmt"
"strings"
"github.com/number571/go-peer/pkg/crypto/hashing"
)
var (
_ IPrivKey = &sRSAPrivKey{}
_ IPubKey = &sRSAPubKey{}
)
const (
cPrivKeyPrefix = "PrivKey{"
cPubKeyPrefix = "PubKey{"
cKeySuffix = "}"
)
/*
* PRIVATE KEY
*/
type sRSAPrivKey struct {
fPubKey IPubKey
fPrivKey *rsa.PrivateKey
}
func newRSAPrivKey(pPrivKey *rsa.PrivateKey) IPrivKey {
return &sRSAPrivKey{
fPubKey: newRSAPubKey(&pPrivKey.PublicKey),
fPrivKey: pPrivKey,
}
}
// Create private key by number of bits.
func NewRSAPrivKey(pBits uint64) IPrivKey {
privKey, err := rsa.GenerateKey(rand.Reader, int(pBits))
if err != nil {
panic(err)
}
return newRSAPrivKey(privKey)
}
func LoadRSAPrivKey(pPrivKey interface{}) IPrivKey {
switch x := pPrivKey.(type) {
case []byte:
privKey := bytesToPrivateKey(x)
if privKey == nil {
return nil
}
return newRSAPrivKey(privKey)
case string:
x = skipSpaceChars(x)
var (
prefix = cPrivKeyPrefix
suffix = cKeySuffix
)
if !strings.HasPrefix(x, prefix) {
return nil
}
x = strings.TrimPrefix(x, prefix)
if !strings.HasSuffix(x, suffix) {
return nil
}
x = strings.TrimSuffix(x, suffix)
pbytes, err := hex.DecodeString(x)
if err != nil {
return nil
}
return LoadRSAPrivKey(pbytes)
default:
panic("unsupported type")
}
}
func (p *sRSAPrivKey) DecryptBytes(pMsg []byte) []byte {
return decryptRSA(p.fPrivKey, pMsg)
}
func (p *sRSAPrivKey) SignBytes(pMsg []byte) []byte {
return sign(p.fPrivKey, hashing.NewSHA256Hasher(pMsg).ToBytes())
}
func (p *sRSAPrivKey) GetPubKey() IPubKey {
return p.fPubKey
}
func (p *sRSAPrivKey) ToBytes() []byte {
return privateKeyToBytes(p.fPrivKey)
}
func (p *sRSAPrivKey) ToString() string {
return fmt.Sprintf(cPrivKeyPrefix+"%X"+cKeySuffix, p.ToBytes())
}
func (p *sRSAPrivKey) GetSize() uint64 {
return p.GetPubKey().GetSize()
}
// Used PKCS1.
func bytesToPrivateKey(pPrivData []byte) *rsa.PrivateKey {
priv, err := x509.ParsePKCS1PrivateKey(pPrivData)
if err != nil {
return nil
}
return priv
}
// Used RSA(OAEP).
func decryptRSA(pPrivKey *rsa.PrivateKey, pData []byte) []byte {
data, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, pPrivKey, pData, nil)
if err != nil {
return nil
}
return data
}
// Used PKCS1.
func privateKeyToBytes(pPrivKey *rsa.PrivateKey) []byte {
return x509.MarshalPKCS1PrivateKey(pPrivKey)
}
func sign(pPrivKey *rsa.PrivateKey, pHash []byte) []byte {
signature, err := rsa.SignPSS(rand.Reader, pPrivKey, crypto.SHA256, pHash, nil)
if err != nil {
return nil
}
return signature
}
/*
* PUBLIC KEY
*/
type sRSAPubKey struct {
fHasher hashing.IHasher
fPubKey *rsa.PublicKey
}
func newRSAPubKey(pPubKey *rsa.PublicKey) IPubKey {
return &sRSAPubKey{
fHasher: newRSAHasher(pPubKey),
fPubKey: pPubKey,
}
}
func LoadRSAPubKey(pPubKey interface{}) IPubKey {
switch x := pPubKey.(type) {
case []byte:
pub := bytesToRSAPublicKey(x)
if pub == nil {
return nil
}
return newRSAPubKey(pub)
case string:
x = skipSpaceChars(x)
var (
prefix = cPubKeyPrefix
suffix = cKeySuffix
)
if !strings.HasPrefix(x, prefix) {
return nil
}
x = strings.TrimPrefix(x, prefix)
if !strings.HasSuffix(x, suffix) {
return nil
}
x = strings.TrimSuffix(x, suffix)
pbytes, err := hex.DecodeString(x)
if err != nil {
return nil
}
return LoadRSAPubKey(pbytes)
default:
panic("unsupported type")
}
}
func (p *sRSAPubKey) EncryptBytes(pMsg []byte) []byte {
return encryptRSA(p.fPubKey, pMsg)
}
func (p *sRSAPubKey) GetHasher() hashing.IHasher {
return p.fHasher
}
func (p *sRSAPubKey) VerifyBytes(pMsg []byte, pSign []byte) bool {
return verifyRSA(p.fPubKey, hashing.NewSHA256Hasher(pMsg).ToBytes(), pSign) == nil
}
func (p *sRSAPubKey) ToBytes() []byte {
return rsaPublicKeyToBytes(p.fPubKey)
}
func (p *sRSAPubKey) ToString() string {
return fmt.Sprintf(cPubKeyPrefix+"%X"+cKeySuffix, p.ToBytes())
}
func (p *sRSAPubKey) GetSize() uint64 {
return uint64(p.fPubKey.N.BitLen())
}
/*
* Address
*/
func newRSAHasher(pPubKey *rsa.PublicKey) hashing.IHasher {
return hashing.NewSHA256Hasher(
rsaPublicKeyToBytes(pPubKey),
)
}
// Used RSA(OAEP).
func encryptRSA(pPubKey *rsa.PublicKey, pData []byte) []byte {
data, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pPubKey, pData, nil)
if err != nil {
return nil
}
return data
}
// Used PKCS1.
func bytesToRSAPublicKey(pPubData []byte) *rsa.PublicKey {
pub, err := x509.ParsePKCS1PublicKey(pPubData)
if err != nil {
return nil
}
return pub
}
// Used PKCS1.
func rsaPublicKeyToBytes(pPubKey *rsa.PublicKey) []byte {
return x509.MarshalPKCS1PublicKey(pPubKey)
}
// Used RSA(PSS).
func verifyRSA(pPubKey *rsa.PublicKey, pHash, pSign []byte) error {
return rsa.VerifyPSS(pPubKey, crypto.SHA256, pHash, pSign, nil)
}
func skipSpaceChars(pS string) string {
s := pS
s = strings.ReplaceAll(s, "\n", "")
s = strings.ReplaceAll(s, "\t", "")
s = strings.ReplaceAll(s, " ", "")
return s
}

View File

@ -1,189 +0,0 @@
// nolint: goerr113
package asymmetric
import (
"bytes"
"errors"
"testing"
"github.com/number571/go-peer/pkg/crypto/random"
)
const (
tcKeySize = 2048
tcPrivKey = `PrivKey{308204A50201000282010100D7114DDEDB12344F4C7086819B91DCE5FE4DD914306BBAFDDA2EB1080A43F98EC0281DD07B5D1F9229DF38E2C986F8CA6B2AC42E4E8E9F021A38E82A03388B4F2314D58D738BB9D77243CC7D8641C574B4CDC00A1D2720329E1162F1EDC7FDA9BF2F9948E927CCF6C274321473E769AA68CB3669729B19BC1CE022E9BA1E0683F3970330ED7FC7F9E836CD1CDB67B571CD98B82FBEB624948E4BD3CF161250311F2661BB6D0885C3E81B66219CB3407619DF239427214328F1C10CC591C490417DB13CB6B90EC22FEC7B7E4BE8B9B3B75E9820D6446AE7F5690CE0ED048DA5ACE47105A1441F4C765CF345499EBFB55B1FFCFE9CAEF2795E3826075AECF2CED502030100010282010100B9E90F7371D44EBBADCC27B9AA0D70F2AFDE03A4DC2684422474F03B8F042B9A26A986FC4D67B67ED70B4B555FF7F8E0A1BB1A531D3D545EB0E4386CF8D3CC38E08E85FBFCC1F02839723A36D7F3CB0893B2B82B06006868D9131681239719C3BEAD1AC858243B9DA38266381FE90F026C0C1E4110FCDA462E7FE22E40E0EBA756B1BC47F9D517D9C92BAC70AFB22DC4B40F31FDDA1F6E854579239C46461D45C3F3E9CDD172BEB8171CE16F04EB20C10A86DCF364A7757FE948061776CD706F1C8B526637B7F53E83D8CDF7B66549A3FD9F6BDDA83A5C499B268EE08D016592BD5854C53D1CD0C85C1E50188817CF16F1EEAF3AD6A064B08B3894639F49C09102818100DFF1AA38A23CBEB84EE566C46CA055BD0382ACBF50EA55B3422A056CC2C07A7F8849252AC375358894D428C7C36BB54E3CDCBA561C49021C41B782B23455E365C48D07F7D7D12FD94BC5239A9B9C4A303CF1025B0207E07388787D6471C785F7E14DD42A9C7F4588ABF54BE793300856C19ACD231183729908F7706931DEE7F302818100F5DA5DEED020D9251B8FCE707442BFBEC2394CDDEDA79E5844D199F0FC2B02D8A4F930EAB2DD13EB7A83EA75500195B15D78846AD7FC72F9EE57CEDF571EB6B4F284F7BC11905EBD8B1D8E4B8DCD3F8D22C21004327662B71C88D8FD97D8221C47F8E7D5F9A8D23737AD49027F9A580D05A9ACF9FA252C8B173EC96D751A281702818100DCDF3FA247F15DB1EEAEB763383813182F642CF92CD752DB50809D851DB835999F537542EE30A6322587F308C3A771D4CE966D7A0CBFBD431D55DFA3DF966E87AB09E637FE3625D94DB00C63AAE2C5113AAA0246BC84044E2EE597D6FF99687A894EF7D9672CE7E9DAA03ED3120AA7CED978D2A6A9D959A7B27E49F296EB611D0281802941E9FD87A3DB8CE4A12F6DA3B507E485478464C1DB1D3186EAFDC07930E69B60A408D77A08ABAD1AB444864754DCC0150582834397B3DBC969A6E7C800F97C482E943C555E3AE7E80E9FB0822D6D7ACBD87143A30C46E89FBB3F5EDF3A800EEAED144ACE48CC6E43C3AABAE69B0A27B5499223A91CCFEACF8DD3D3B091212502818100C68D284CAC625B8AB21E2ABDC62B418C66F8E707402F763F4087C55BCAE98197C2D9829E3136FCE952A240230CDCB993BF6BDEF1178CEE8E7305CF538F42687B2CB57497187C885DCC38E4988D9FCDFAA5D505A85056FA248D6638E236FFBB68C34A7FC119ED3EC5270317DD39D3B9A6440C4094403466EE23FDE541F01DB2F8}`
tcPubKey = `PubKey{3082010A0282010100D7114DDEDB12344F4C7086819B91DCE5FE4DD914306BBAFDDA2EB1080A43F98EC0281DD07B5D1F9229DF38E2C986F8CA6B2AC42E4E8E9F021A38E82A03388B4F2314D58D738BB9D77243CC7D8641C574B4CDC00A1D2720329E1162F1EDC7FDA9BF2F9948E927CCF6C274321473E769AA68CB3669729B19BC1CE022E9BA1E0683F3970330ED7FC7F9E836CD1CDB67B571CD98B82FBEB624948E4BD3CF161250311F2661BB6D0885C3E81B66219CB3407619DF239427214328F1C10CC591C490417DB13CB6B90EC22FEC7B7E4BE8B9B3B75E9820D6446AE7F5690CE0ED048DA5ACE47105A1441F4C765CF345499EBFB55B1FFCFE9CAEF2795E3826075AECF2CED50203010001}`
tcAddr = "82bd6fdab3f4141bbd11fec786c7d3cc68b557fc1c96022791d3d34ae038ea1e"
)
func TestLoadRSAKeyUnknownType(t *testing.T) {
t.Parallel()
for i := 0; i < 2; i++ {
testLoadKeyUnknownType(t, i)
}
}
func testLoadKeyUnknownType(t *testing.T, n int) {
defer func() {
if r := recover(); r == nil {
t.Error("nothing panics")
return
}
}()
switch n {
case 0:
_ = LoadRSAPrivKey(struct{}{})
case 1:
_ = LoadRSAPubKey(struct{}{})
}
}
func TestLoadRSAKey(t *testing.T) {
t.Parallel()
priv := LoadRSAPrivKey(tcPrivKey)
if priv == nil {
t.Error("failed load private key")
return
}
if priv := LoadRSAPrivKey([]byte{123}); priv != nil {
t.Error("success load invalid private key (bytes)")
return
}
str := string("123")
if priv := LoadRSAPrivKey(str); priv != nil {
t.Error("success load invalid private key (string)")
return
}
prefix := cPrivKeyPrefix
if priv := LoadRSAPrivKey(prefix + str); priv != nil {
t.Error("success load invalid private key (string+prefix)")
return
}
suffix := cKeySuffix
if priv := LoadRSAPrivKey(prefix + str + suffix); priv != nil {
t.Error("success load invalid private key (string+prefix+suffix)")
return
}
pub := LoadRSAPubKey(tcPubKey)
if pub == nil {
t.Error("failed load public key")
return
}
if pub := LoadRSAPubKey([]byte{123}); pub != nil {
t.Error("success load invalid public key (bytes)")
return
}
if pub := LoadRSAPubKey(str); pub != nil {
t.Error("success load invalid public key (string)")
return
}
prefixPub := cPubKeyPrefix
if pub := LoadRSAPubKey(prefixPub + str); pub != nil {
t.Error("success load invalid public key (string+prefix)")
return
}
if pub := LoadRSAPubKey(prefixPub + str + suffix); pub != nil {
t.Error("success load invalid public key (string+prefix+suffix)")
return
}
if priv.GetPubKey().GetHasher().ToString() != pub.GetHasher().ToString() {
t.Error("load public key have not relation with private key")
return
}
if err := testRSAConverter(priv, pub); err != nil {
t.Error(err)
return
}
}
func testRSAConverter(priv IPrivKey, pub IPubKey) error {
if priv.GetSize() != tcKeySize {
return errors.New("private key size != tcKeySize")
}
if pub.GetSize() != tcKeySize {
return errors.New("public key size != tcKeySize")
}
if priv.ToString() != tcPrivKey {
return errors.New("private key string != tcPrivKey")
}
if pub.ToString() != tcPubKey {
return errors.New("public key string != tcPrivKey")
}
if pub.GetHasher().ToString() != tcAddr {
return errors.New("address string != tcAddr")
}
return nil
}
func TestRSASign(t *testing.T) {
t.Parallel()
var (
priv = NewRSAPrivKey(1024)
msg = []byte("hello, world!")
)
pub := priv.GetPubKey()
sign := priv.SignBytes(msg)
if !pub.VerifyBytes(msg, sign) {
t.Error("signature is invalid")
return
}
if pub.VerifyBytes(msg, []byte{123}) {
t.Error("success verify with invalid signature")
return
}
if pub.VerifyBytes([]byte{123}, msg) {
t.Error("success verify with invalid message")
return
}
}
func TestRSAEncrypt(t *testing.T) {
t.Parallel()
var (
priv = NewRSAPrivKey(1024)
msg = []byte("hello, world!")
)
pub := priv.GetPubKey()
if enc := pub.EncryptBytes(random.NewCSPRNG().GetBytes(1 << 10)); enc != nil {
t.Error("success encrypt message with size > key size")
return
}
emsg := pub.EncryptBytes(msg)
if !bytes.Equal(msg, priv.DecryptBytes(emsg)) {
t.Error("decrypted message is invalid")
return
}
if dec := priv.DecryptBytes([]byte{123}); dec != nil {
t.Error("success decrypt invalid message")
return
}
}

View File

@ -1,4 +1,4 @@
// Package asymmetric is a wrapper on standard Go package - rsa.
// Package asymmetric is a wrapper on Go circl packages - kyber, dilithium.
//
// The package also adds an additional interface for working with a list of public keys.
package asymmetric

View File

@ -0,0 +1,97 @@
package asymmetric
import (
"crypto/rand"
"github.com/cloudflare/circl/kem"
kyber "github.com/cloudflare/circl/kem/kyber/kyber768"
)
const (
CKEncSize = kyber.CiphertextSize
)
var (
_ IKEncPrivKey = &sKyber768PrivKey{}
_ IKEncPubKey = &sKyber768PubKey{}
)
type sKyber768PrivKey struct {
fPrivKey *kyber.PrivateKey
fPubKey *sKyber768PubKey
}
type sKyber768PubKey struct {
fK *kyber.PublicKey
}
func NewKEncPrivKey() IKEncPrivKey {
_, privKey, err := kyber.GenerateKeyPair(rand.Reader)
if err != nil {
panic(err)
}
return newKEncPrivKey(privKey)
}
func newKEncPrivKey(privKey kem.PrivateKey) *sKyber768PrivKey {
pk, ok := privKey.(*kyber.PrivateKey)
if !ok {
return nil
}
return &sKyber768PrivKey{
fPrivKey: pk,
fPubKey: newKEncPubKey(privKey.Public()),
}
}
func newKEncPubKey(pubKey kem.PublicKey) *sKyber768PubKey {
pk, ok := pubKey.(*kyber.PublicKey)
if !ok {
return nil
}
return &sKyber768PubKey{pk}
}
func LoadKEncPrivKey(pBytes []byte) IKEncPrivKey {
privKey, err := kyber.Scheme().UnmarshalBinaryPrivateKey(pBytes)
if err != nil {
return nil
}
return newKEncPrivKey(privKey)
}
func LoadKEncPubKey(pBytes []byte) IKEncPubKey {
pubKey, err := kyber.Scheme().UnmarshalBinaryPublicKey(pBytes)
if err != nil {
return nil
}
return newKEncPubKey(pubKey)
}
func (p *sKyber768PubKey) Encapsulate() ([]byte, []byte, error) {
return kyber.Scheme().Encapsulate(p.fK)
}
func (p *sKyber768PubKey) ToBytes() []byte {
b, err := p.fK.MarshalBinary()
if err != nil {
panic(err)
}
return b
}
func (p *sKyber768PrivKey) GetPubKey() IKEncPubKey {
return p.fPubKey
}
func (p *sKyber768PrivKey) Decapsulate(pCiphertext []byte) ([]byte, error) {
return kyber.Scheme().Decapsulate(p.fPrivKey, pCiphertext)
}
func (p *sKyber768PrivKey) ToBytes() []byte {
b, err := p.fPrivKey.MarshalBinary()
if err != nil {
panic(err)
}
return b
}

View File

@ -1,4 +1,4 @@
package quantum
package asymmetric
import (
"bytes"
@ -8,11 +8,11 @@ import (
func TestKEM(t *testing.T) {
t.Parallel()
privKey := NewKEMPrivKey()
privKey = LoadKEMPrivKey(privKey.ToBytes())
privKey := NewKEncPrivKey()
privKey = LoadKEncPrivKey(privKey.ToBytes())
pubKey := privKey.GetPubKey()
pubKey = LoadKEMPubKey(pubKey.ToBytes())
pubKey = LoadKEncPubKey(pubKey.ToBytes())
ct, ss1, err := pubKey.Encapsulate()
if err != nil {

View File

@ -1,4 +1,4 @@
package quantum
package asymmetric
import (
"encoding/hex"
@ -18,17 +18,17 @@ var (
)
type sPrivKeyChain struct {
fKEM IKEMPrivKey
fSigner ISignerPrivKey
fKEM IKEncPrivKey
fSigner ISignPrivKey
fPubKeyChain IPubKeyChain
}
type sPubKeyChain struct {
fKEM IKEMPubKey
fSigner ISignerPubKey
fKEM IKEncPubKey
fSigner ISignPubKey
}
func NewPrivKeyChain(pKEM IKEMPrivKey, pSigner ISignerPrivKey) IPrivKeyChain {
func NewPrivKeyChain(pKEM IKEncPrivKey, pSigner ISignPrivKey) IPrivKeyChain {
return &sPrivKeyChain{
fKEM: pKEM,
fSigner: pSigner,
@ -61,7 +61,7 @@ func LoadPrivKeyChain(pKeychain string) IPrivKeyChain {
if err != nil {
return nil
}
kemPrivKey := LoadKEMPrivKey(pbytesKEM)
kemPrivKey := LoadKEncPrivKey(pbytesKEM)
if kemPrivKey == nil {
return nil
}
@ -70,7 +70,7 @@ func LoadPrivKeyChain(pKeychain string) IPrivKeyChain {
if err != nil {
return nil
}
signerPrivKey := LoadSignerPrivKey(pbytesSigner)
signerPrivKey := LoadSignPrivKey(pbytesSigner)
if signerPrivKey == nil {
return nil
}
@ -82,15 +82,15 @@ func (p *sPrivKeyChain) ToString() string {
return fmt.Sprintf("%s%X;%X%s", cPrivKeyPrefix, p.fKEM.ToBytes(), p.fSigner.ToBytes(), cKeySuffix)
}
func (p *sPrivKeyChain) GetKEMPrivKey() IKEMPrivKey {
func (p *sPrivKeyChain) GetKEncPrivKey() IKEncPrivKey {
return p.fKEM
}
func (p *sPrivKeyChain) GetSignerPrivKey() ISignerPrivKey {
func (p *sPrivKeyChain) GetSignPrivKey() ISignPrivKey {
return p.fSigner
}
func NewPubKeyChain(pKEM IKEMPubKey, pSigner ISignerPubKey) IPubKeyChain {
func NewPubKeyChain(pKEM IKEncPubKey, pSigner ISignPubKey) IPubKeyChain {
return &sPubKeyChain{
fKEM: pKEM,
fSigner: pSigner,
@ -118,7 +118,7 @@ func LoadPubKeyChain(pKeychain string) IPubKeyChain {
if err != nil {
return nil
}
kemPubKey := LoadKEMPubKey(pbytesKEM)
kemPubKey := LoadKEncPubKey(pbytesKEM)
if kemPubKey == nil {
return nil
}
@ -127,7 +127,7 @@ func LoadPubKeyChain(pKeychain string) IPubKeyChain {
if err != nil {
return nil
}
signerPubKey := LoadSignerPubKey(pbytesSigner)
signerPubKey := LoadSignPubKey(pbytesSigner)
if signerPubKey == nil {
return nil
}
@ -139,11 +139,11 @@ func (p *sPubKeyChain) ToString() string {
return fmt.Sprintf("%s%X;%X%s", cPubKeyPrefix, p.fKEM.ToBytes(), p.fSigner.ToBytes(), cKeySuffix)
}
func (p *sPubKeyChain) GetKEMPubKey() IKEMPubKey {
func (p *sPubKeyChain) GetKEncPubKey() IKEncPubKey {
return p.fKEM
}
func (p *sPubKeyChain) GetSignerPubKey() ISignerPubKey {
func (p *sPubKeyChain) GetSignPubKey() ISignPubKey {
return p.fSigner
}

View File

@ -1,4 +1,4 @@
package quantum
package asymmetric
import (
"bytes"
@ -8,22 +8,22 @@ import (
func TestPrivKeyChain(t *testing.T) {
t.Parallel()
kemPrivKey := NewKEMPrivKey()
signerPrivKey := NewSignerPrivKey()
kemPrivKey := NewKEncPrivKey()
signerPrivKey := NewSignPrivKey()
keychain := NewPrivKeyChain(kemPrivKey, signerPrivKey)
if !bytes.Equal(kemPrivKey.ToBytes(), keychain.GetKEMPrivKey().ToBytes()) {
if !bytes.Equal(kemPrivKey.ToBytes(), keychain.GetKEncPrivKey().ToBytes()) {
t.Error("invalid kem priv key (1)")
}
if !bytes.Equal(signerPrivKey.ToBytes(), keychain.GetSignerPrivKey().ToBytes()) {
if !bytes.Equal(signerPrivKey.ToBytes(), keychain.GetSignPrivKey().ToBytes()) {
t.Error("invalid signer priv key (1)")
}
keychain = LoadPrivKeyChain(keychain.ToString())
if !bytes.Equal(kemPrivKey.ToBytes(), keychain.GetKEMPrivKey().ToBytes()) {
if !bytes.Equal(kemPrivKey.ToBytes(), keychain.GetKEncPrivKey().ToBytes()) {
t.Error("invalid kem priv key (2)")
}
if !bytes.Equal(signerPrivKey.ToBytes(), keychain.GetSignerPrivKey().ToBytes()) {
if !bytes.Equal(signerPrivKey.ToBytes(), keychain.GetSignPrivKey().ToBytes()) {
t.Error("invalid signer priv key (2)")
}
@ -33,22 +33,22 @@ func TestPrivKeyChain(t *testing.T) {
func TestPubKeyChain(t *testing.T) {
t.Parallel()
kemPubKey := NewKEMPrivKey().GetPubKey()
signerPubKey := NewSignerPrivKey().GetPubKey()
kemPubKey := NewKEncPrivKey().GetPubKey()
signerPubKey := NewSignPrivKey().GetPubKey()
keychain := NewPubKeyChain(kemPubKey, signerPubKey)
if !bytes.Equal(kemPubKey.ToBytes(), keychain.GetKEMPubKey().ToBytes()) {
if !bytes.Equal(kemPubKey.ToBytes(), keychain.GetKEncPubKey().ToBytes()) {
t.Error("invalid kem pub key (1)")
}
if !bytes.Equal(signerPubKey.ToBytes(), keychain.GetSignerPubKey().ToBytes()) {
if !bytes.Equal(signerPubKey.ToBytes(), keychain.GetSignPubKey().ToBytes()) {
t.Error("invalid signer pub key (1)")
}
keychain = LoadPubKeyChain(keychain.ToString())
if !bytes.Equal(kemPubKey.ToBytes(), keychain.GetKEMPubKey().ToBytes()) {
if !bytes.Equal(kemPubKey.ToBytes(), keychain.GetKEncPubKey().ToBytes()) {
t.Error("invalid kem pub key (2)")
}
if !bytes.Equal(signerPubKey.ToBytes(), keychain.GetSignerPubKey().ToBytes()) {
if !bytes.Equal(signerPubKey.ToBytes(), keychain.GetSignPubKey().ToBytes()) {
t.Error("invalid signer pub key (2)")
}

View File

@ -1,4 +1,4 @@
package quantum
package asymmetric
import (
"sync"
@ -23,11 +23,11 @@ func NewListPubKeyChains() IListPubKeyChains {
}
// Check the existence of a friend in the list by the public key.
func (p *sListPubKeyChains) GetPubKeyChain(pSignerPubKey ISignerPubKey) (IPubKeyChain, bool) {
func (p *sListPubKeyChains) GetPubKeyChain(pSignPubKey ISignPubKey) (IPubKeyChain, bool) {
p.fMutex.RLock()
defer p.fMutex.RUnlock()
keychain, ok := p.fMapping[hashkey(pSignerPubKey)]
keychain, ok := p.fMapping[hashkey(pSignPubKey)]
return keychain, ok
}
@ -49,7 +49,7 @@ func (p *sListPubKeyChains) AddPubKeyChain(pPubKeyChain IPubKeyChain) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
p.fMapping[hashkey(pPubKeyChain.GetSignerPubKey())] = pPubKeyChain
p.fMapping[hashkey(pPubKeyChain.GetSignPubKey())] = pPubKeyChain
}
// Delete public key from list of friends.
@ -57,11 +57,11 @@ func (p *sListPubKeyChains) DelPubKeyChain(pPubKeyChain IPubKeyChain) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
delete(p.fMapping, hashkey(pPubKeyChain.GetSignerPubKey()))
delete(p.fMapping, hashkey(pPubKeyChain.GetSignPubKey()))
}
func hashkey(pSignerPubKey ISignerPubKey) string {
return hashing.NewSHA256Hasher(
pSignerPubKey.ToBytes(),
func hashkey(pSignPubKey ISignPubKey) string {
return hashing.NewHasher(
pSignPubKey.ToBytes(),
).ToString()
}

View File

@ -1,59 +0,0 @@
package asymmetric
import (
"sync"
)
var (
_ IListPubKeys = &sListPubKeys{}
)
// F2F connection mode.
type sListPubKeys struct {
fMutex sync.RWMutex
fMapping map[string]IPubKey
}
func NewListPubKeys() IListPubKeys {
return &sListPubKeys{
fMapping: make(map[string]IPubKey),
}
}
// Check the existence of a friend in the list by the public key.
func (p *sListPubKeys) InPubKeys(pPubKey IPubKey) bool {
p.fMutex.RLock()
defer p.fMutex.RUnlock()
_, ok := p.fMapping[pPubKey.GetHasher().ToString()]
return ok
}
// Get a list of friends public keys.
func (p *sListPubKeys) GetPubKeys() []IPubKey {
p.fMutex.RLock()
defer p.fMutex.RUnlock()
list := make([]IPubKey, 0, len(p.fMapping))
for _, pub := range p.fMapping {
list = append(list, pub)
}
return list
}
// Add public key to list of friends.
func (p *sListPubKeys) AddPubKey(pPubKey IPubKey) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
p.fMapping[pPubKey.GetHasher().ToString()] = pPubKey
}
// Delete public key from list of friends.
func (p *sListPubKeys) DelPubKey(pub IPubKey) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
delete(p.fMapping, pub.GetHasher().ToString())
}

View File

@ -1,46 +0,0 @@
package asymmetric
import (
"testing"
testutils "github.com/number571/go-peer/test/utils"
)
var (
tgPubKeys = [3]IPubKey{
LoadRSAPubKey(testutils.TgPubKeys[0]),
LoadRSAPubKey(testutils.TgPubKeys[1]),
LoadRSAPubKey(testutils.TgPubKeys[2]),
}
)
func TestFriends(t *testing.T) {
t.Parallel()
list := NewListPubKeys()
list.AddPubKey(tgPubKeys[0])
list.AddPubKey(tgPubKeys[1])
list.AddPubKey(tgPubKeys[2])
if len(list.GetPubKeys()) != 3 {
t.Error("len f2f list != 3")
return
}
list.DelPubKey(tgPubKeys[1])
if len(list.GetPubKeys()) != 2 {
t.Error("len f2f list != 2 after remove")
return
}
if list.InPubKeys(tgPubKeys[1]) {
t.Error("deleted value in list")
return
}
if !list.InPubKeys(tgPubKeys[2]) {
t.Error("undefined exist value")
return
}
}

View File

@ -0,0 +1,94 @@
package asymmetric
import (
"crypto"
"crypto/rand"
"github.com/cloudflare/circl/sign"
dilithium "github.com/cloudflare/circl/sign/dilithium/mode3"
)
const (
CSignSize = dilithium.SignatureSize
)
var (
_ ISignPrivKey = &sDilithiumM3PrivKey{}
_ ISignPubKey = &sDilithiumM3PubKey{}
)
type sDilithiumM3PrivKey struct {
fPrivKey *dilithium.PrivateKey
fPubKey *sDilithiumM3PubKey
}
type sDilithiumM3PubKey struct {
fPubKey *dilithium.PublicKey
}
func NewSignPrivKey() ISignPrivKey {
_, privKey, err := dilithium.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
return newSignPrivKey(privKey)
}
func LoadSignPrivKey(pBytes []byte) ISignPrivKey {
privKey, err := dilithium.Scheme().UnmarshalBinaryPrivateKey(pBytes)
if err != nil {
return nil
}
return newSignPrivKey(privKey)
}
func LoadSignPubKey(pBytes []byte) ISignPubKey {
pubKey, err := dilithium.Scheme().UnmarshalBinaryPublicKey(pBytes)
if err != nil {
return nil
}
return newSignPubKey(pubKey)
}
func newSignPrivKey(privKey sign.PrivateKey) *sDilithiumM3PrivKey {
pk, ok := privKey.(*dilithium.PrivateKey)
if !ok {
return nil
}
return &sDilithiumM3PrivKey{
fPrivKey: pk,
fPubKey: newSignPubKey(privKey.Public()),
}
}
func newSignPubKey(pubKey crypto.PublicKey) *sDilithiumM3PubKey {
pk, ok := pubKey.(*dilithium.PublicKey)
if !ok {
return nil
}
return &sDilithiumM3PubKey{pk}
}
func (p *sDilithiumM3PrivKey) GetPubKey() ISignPubKey {
return p.fPubKey
}
func (p *sDilithiumM3PrivKey) ToBytes() []byte {
return p.fPrivKey.Bytes()
}
func (p *sDilithiumM3PrivKey) SignBytes(pMsg []byte) []byte {
sign, err := p.fPrivKey.Sign(rand.Reader, pMsg, crypto.Hash(0))
if err != nil {
panic(err)
}
return sign
}
func (p *sDilithiumM3PubKey) VerifyBytes(pMsg, pSign []byte) bool {
return dilithium.Verify(p.fPubKey, pMsg, pSign)
}
func (p *sDilithiumM3PubKey) ToBytes() []byte {
return p.fPubKey.Bytes()
}

View File

@ -1,4 +1,4 @@
package quantum
package asymmetric
import (
"testing"
@ -7,11 +7,11 @@ import (
func TestSigner(t *testing.T) {
t.Parallel()
privKey := NewSignerPrivKey()
privKey = LoadSignerPrivKey(privKey.ToBytes())
privKey := NewSignPrivKey()
privKey = LoadSignPrivKey(privKey.ToBytes())
pubKey := privKey.GetPubKey()
pubKey = LoadSignerPubKey(pubKey.ToBytes())
pubKey = LoadSignPubKey(pubKey.ToBytes())
msg := []byte("hello, world!")
sign := privKey.SignBytes(msg)

View File

@ -1,32 +1,43 @@
package asymmetric
import (
"github.com/number571/go-peer/pkg/crypto"
"github.com/number571/go-peer/pkg/crypto/hashing"
"github.com/number571/go-peer/pkg/types"
)
type IListPubKeys interface {
InPubKeys(IPubKey) bool
GetPubKeys() []IPubKey
AddPubKey(IPubKey)
DelPubKey(IPubKey)
type IListPubKeyChains interface {
AllPubKeyChains() []IPubKeyChain
GetPubKeyChain(ISignPubKey) (IPubKeyChain, bool)
AddPubKeyChain(IPubKeyChain)
DelPubKeyChain(IPubKeyChain)
}
type IPubKey interface {
crypto.IEncrypter
types.IConverter
GetSize() uint64
type IPrivKeyChain interface {
ToString() string
GetPubKeyChain() IPubKeyChain
GetKEncPrivKey() IKEncPrivKey
GetSignPrivKey() ISignPrivKey
}
GetHasher() hashing.IHasher
type IPubKeyChain interface {
ToString() string
GetKEncPubKey() IKEncPubKey
GetSignPubKey() ISignPubKey
}
type IKEncPrivKey interface {
ToBytes() []byte
GetPubKey() IKEncPubKey
Decapsulate([]byte) ([]byte, error)
}
type IKEncPubKey interface {
Encapsulate() ([]byte, []byte, error)
ToBytes() []byte
}
type ISignPrivKey interface {
ToBytes() []byte
GetPubKey() ISignPubKey
SignBytes([]byte) []byte
}
type ISignPubKey interface {
ToBytes() []byte
VerifyBytes([]byte, []byte) bool
}
type IPrivKey interface {
crypto.IDecrypter
types.IConverter
GetSize() uint64
SignBytes([]byte) []byte
GetPubKey() IPubKey
}

View File

@ -1,7 +1,7 @@
// Package crypto represents wrapper functions and interfaces over cryptographic primitives.
//
// A package consists of many sub-packages:
// 1. asymmetric - asymmetric message encryption, message signing,
// 1. quantum - asymmetric KEM, message signing,
// 2. hashing - message hashing and message authentication code,
// 3. keybuilder - generating a key from a password,
// 4. puzzle - solving complex mathematical problems,

View File

@ -1,35 +1,35 @@
package hashing
import (
"crypto/sha256"
"crypto/sha512"
"github.com/number571/go-peer/pkg/encoding"
)
var (
_ IHasher = &sSHA256Hasher{}
_ IHasher = &sSHA512Hasher{}
)
const (
CSHA256Size = sha256.Size
CHasherSize = sha512.Size
)
type sSHA256Hasher struct {
type sSHA512Hasher struct {
fHash []byte
}
func NewSHA256Hasher(pData []byte) IHasher {
h := sha256.New()
func NewHasher(pData []byte) IHasher {
h := sha512.New()
h.Write(pData)
return &sSHA256Hasher{
return &sSHA512Hasher{
fHash: h.Sum(nil),
}
}
func (p *sSHA256Hasher) ToString() string {
func (p *sSHA512Hasher) ToString() string {
return encoding.HexEncode(p.ToBytes())
}
func (p *sSHA256Hasher) ToBytes() []byte {
func (p *sSHA512Hasher) ToBytes() []byte {
return p.fHash
}

View File

@ -7,14 +7,14 @@ func TestSHA256(t *testing.T) {
msg := []byte("hello, world!")
hash := NewSHA256Hasher(msg).ToString()
if hash != NewSHA256Hasher(msg).ToString() {
hash := NewHasher(msg).ToString()
if hash != NewHasher(msg).ToString() {
t.Error("hash is not determined")
return
}
msg[3] ^= 8
if hash == NewSHA256Hasher(msg).ToString() {
if hash == NewHasher(msg).ToString() {
t.Error("bit didn't change the result ")
return
}
@ -26,14 +26,14 @@ func TestHMACSHA256(t *testing.T) {
key := []byte("secret key")
msg := []byte("hello, world!")
hash := NewHMACSHA256Hasher(key, msg).ToString()
if hash != NewHMACSHA256Hasher(key, msg).ToString() {
hash := NewHMACHasher(key, msg).ToString()
if hash != NewHMACHasher(key, msg).ToString() {
t.Error("hash is not determined")
return
}
msg[3] ^= 8
if hash == NewHMACSHA256Hasher(key, msg).ToString() {
if hash == NewHMACHasher(key, msg).ToString() {
t.Error("bit didn't change the result")
return
}

View File

@ -2,31 +2,31 @@ package hashing
import (
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"github.com/number571/go-peer/pkg/encoding"
)
var (
_ IHasher = &sHMACSHA256Hasher{}
_ IHasher = &sHMACSHA512Hasher{}
)
type sHMACSHA256Hasher struct {
type sHMACSHA512Hasher struct {
fHash []byte
}
func NewHMACSHA256Hasher(pKey []byte, pData []byte) IHasher {
h := hmac.New(sha256.New, pKey)
func NewHMACHasher(pKey []byte, pData []byte) IHasher {
h := hmac.New(sha512.New, pKey)
h.Write(pData)
return &sHMACSHA256Hasher{
return &sHMACSHA512Hasher{
fHash: h.Sum(nil),
}
}
func (p *sHMACSHA256Hasher) ToString() string {
func (p *sHMACSHA512Hasher) ToString() string {
return encoding.HexEncode(p.ToBytes())
}
func (p *sHMACSHA256Hasher) ToBytes() []byte {
func (p *sHMACSHA512Hasher) ToBytes() []byte {
return p.fHash
}

View File

@ -1,7 +1,7 @@
package keybuilder
import (
"crypto/sha256"
"crypto/sha512"
"golang.org/x/crypto/pbkdf2"
)
@ -28,6 +28,6 @@ func (p *sKeyBuilder) Build(pPassword string, pKeyLen uint64) []byte {
p.fSalt,
int(p.fIterN),
int(pKeyLen),
sha256.New,
sha512.New,
)
}

View File

@ -10,7 +10,7 @@ import (
const (
tcKeySize = 32
tcHash = "8d47725f8604cb2e8f1be5e0b49ef143ea62625dd37ea4ce5f24501a32591784"
tcHash = "0aac5a0a082dcbc64befb61c798549126cd6b4075081debc6636c53c941c5cb0"
)
func TestKeyBuilder(t *testing.T) {

View File

@ -11,7 +11,7 @@ import (
)
const (
cHashSizeInBits = hashing.CSHA256Size * 8
cHashSizeInBits = hashing.CHasherSize * 8
)
var (
@ -62,7 +62,7 @@ func (p *sPoWPuzzle) ProofBytes(pPackHash []byte, pParallel uint64) uint64 {
return
default:
bNonce := encoding.Uint64ToBytes(nonce)
hash := hashing.NewSHA256Hasher(bytes.Join(
hash := hashing.NewHasher(bytes.Join(
[][]byte{packHash, bNonce[:]},
[]byte{},
)).ToBytes()
@ -93,7 +93,7 @@ func (p *sPoWPuzzle) VerifyBytes(pPackHash []byte, pNonce uint64) bool {
target.Lsh(target, cHashSizeInBits-uint(p.fDiff))
bNonce := encoding.Uint64ToBytes(pNonce)
hash := hashing.NewSHA256Hasher(bytes.Join(
hash := hashing.NewHasher(bytes.Join(
[][]byte{packHash, bNonce[:]},
[]byte{},
)).ToBytes()

View File

@ -29,7 +29,7 @@ func TestPuzzle(t *testing.T) {
msg = []byte("hello, world!")
)
hash := hashing.NewSHA256Hasher(msg).ToBytes()
hash := hashing.NewHasher(msg).ToBytes()
proof := puzzle.ProofBytes(hash, 1)
if !puzzle.VerifyBytes(hash, proof) {

View File

@ -1,4 +0,0 @@
// Package asymmetric is a wrapper on Go circl packages - kyber, dilithium.
//
// The package also adds an additional interface for working with a list of public keys.
package quantum

View File

@ -1,89 +0,0 @@
package quantum
import (
"crypto/rand"
"github.com/cloudflare/circl/kem"
kyber "github.com/cloudflare/circl/kem/kyber/kyber768"
)
const (
CCiphertextSize = kyber.CiphertextSize
)
var (
_ IKEMPrivKey = &sKEMPrivKey{}
_ IKEMPubKey = &sKEMPubKey{}
)
type sKEMPrivKey struct {
fPrivKey *kyber.PrivateKey
fPubKey *sKEMPubKey
}
type sKEMPubKey struct {
fK *kyber.PublicKey
}
func NewKEMPrivKey() IKEMPrivKey {
_, privKey, err := kyber.GenerateKeyPair(rand.Reader)
if err != nil {
panic(err)
}
return newKEMPrivKey(privKey)
}
func newKEMPrivKey(privKey kem.PrivateKey) *sKEMPrivKey {
return &sKEMPrivKey{
fPrivKey: privKey.(*kyber.PrivateKey),
fPubKey: newKEMPubKey(privKey.Public()),
}
}
func newKEMPubKey(pubKey kem.PublicKey) *sKEMPubKey {
return &sKEMPubKey{pubKey.(*kyber.PublicKey)}
}
func LoadKEMPrivKey(pBytes []byte) IKEMPrivKey {
privKey, err := kyber.Scheme().UnmarshalBinaryPrivateKey(pBytes)
if err != nil {
return nil
}
return newKEMPrivKey(privKey)
}
func LoadKEMPubKey(pBytes []byte) IKEMPubKey {
pubKey, err := kyber.Scheme().UnmarshalBinaryPublicKey(pBytes)
if err != nil {
return nil
}
return newKEMPubKey(pubKey)
}
func (p *sKEMPubKey) Encapsulate() ([]byte, []byte, error) {
return kyber.Scheme().Encapsulate(p.fK)
}
func (p *sKEMPubKey) ToBytes() []byte {
b, err := p.fK.MarshalBinary()
if err != nil {
panic(err)
}
return b
}
func (p *sKEMPrivKey) GetPubKey() IKEMPubKey {
return p.fPubKey
}
func (p *sKEMPrivKey) Decapsulate(pCiphertext []byte) ([]byte, error) {
return kyber.Scheme().Decapsulate(p.fPrivKey, pCiphertext)
}
func (p *sKEMPrivKey) ToBytes() []byte {
b, err := p.fPrivKey.MarshalBinary()
if err != nil {
panic(err)
}
return b
}

View File

@ -1,86 +0,0 @@
package quantum
import (
"crypto"
"crypto/rand"
"github.com/cloudflare/circl/sign"
dilithium "github.com/cloudflare/circl/sign/dilithium/mode3"
)
const (
CSignatureSize = dilithium.SignatureSize
)
var (
_ ISignerPrivKey = &sSignerPrivKey{}
_ ISignerPubKey = &sSignerPubKey{}
)
type sSignerPrivKey struct {
fPrivKey *dilithium.PrivateKey
fPubKey *sSignerPubKey
}
type sSignerPubKey struct {
fPubKey *dilithium.PublicKey
}
func NewSignerPrivKey() ISignerPrivKey {
_, privKey, err := dilithium.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
return newSignerPrivKey(privKey)
}
func LoadSignerPrivKey(pBytes []byte) ISignerPrivKey {
privKey, err := dilithium.Scheme().UnmarshalBinaryPrivateKey(pBytes)
if err != nil {
return nil
}
return newSignerPrivKey(privKey)
}
func LoadSignerPubKey(pBytes []byte) ISignerPubKey {
pubKey, err := dilithium.Scheme().UnmarshalBinaryPublicKey(pBytes)
if err != nil {
return nil
}
return newSignerPubKey(pubKey)
}
func newSignerPrivKey(privKey sign.PrivateKey) *sSignerPrivKey {
return &sSignerPrivKey{
fPrivKey: privKey.(*dilithium.PrivateKey),
fPubKey: newSignerPubKey(privKey.Public()),
}
}
func newSignerPubKey(pubKey crypto.PublicKey) *sSignerPubKey {
return &sSignerPubKey{pubKey.(*dilithium.PublicKey)}
}
func (p *sSignerPrivKey) GetPubKey() ISignerPubKey {
return p.fPubKey
}
func (p *sSignerPrivKey) ToBytes() []byte {
return p.fPrivKey.Bytes()
}
func (p *sSignerPrivKey) SignBytes(pMsg []byte) []byte {
sign, err := p.fPrivKey.Sign(rand.Reader, pMsg, crypto.Hash(0))
if err != nil {
panic(err)
}
return sign
}
func (p *sSignerPubKey) VerifyBytes(pMsg, pSign []byte) bool {
return dilithium.Verify(p.fPubKey, pMsg, pSign)
}
func (p *sSignerPubKey) ToBytes() []byte {
return p.fPubKey.Bytes()
}

View File

@ -1,43 +0,0 @@
package quantum
type IListPubKeyChains interface {
AllPubKeyChains() []IPubKeyChain
GetPubKeyChain(ISignerPubKey) (IPubKeyChain, bool)
AddPubKeyChain(IPubKeyChain)
DelPubKeyChain(IPubKeyChain)
}
type IPrivKeyChain interface {
ToString() string
GetPubKeyChain() IPubKeyChain
GetKEMPrivKey() IKEMPrivKey
GetSignerPrivKey() ISignerPrivKey
}
type IPubKeyChain interface {
ToString() string
GetKEMPubKey() IKEMPubKey
GetSignerPubKey() ISignerPubKey
}
type IKEMPrivKey interface {
ToBytes() []byte
GetPubKey() IKEMPubKey
Decapsulate([]byte) ([]byte, error)
}
type IKEMPubKey interface {
Encapsulate() ([]byte, []byte, error)
ToBytes() []byte
}
type ISignerPrivKey interface {
ToBytes() []byte
GetPubKey() ISignerPubKey
SignBytes([]byte) []byte
}
type ISignerPubKey interface {
ToBytes() []byte
VerifyBytes([]byte, []byte) bool
}

View File

@ -13,18 +13,18 @@ const (
)
var (
_ IPRNG = &sCSPRNG{}
_ IRandom = &sRandom{}
)
type sCSPRNG struct {
type sRandom struct {
}
func NewCSPRNG() IPRNG {
return &sCSPRNG{}
func NewRandom() IRandom {
return &sRandom{}
}
// Generates a cryptographically strong pseudo-random bytes.
func (p *sCSPRNG) GetBytes(n uint64) []byte {
func (p *sRandom) GetBytes(n uint64) []byte {
slice := make([]byte, n)
if _, err := rand.Read(slice); err != nil {
panic(err) // 'return nil' is insecure
@ -47,7 +47,7 @@ func (p *sCSPRNG) GetBytes(n uint64) []byte {
security[p=128] = random(32) hex_byte
security[p=128] = random(21.(3)) cur_byte
*/
func (p *sCSPRNG) GetString(n uint64) string {
func (p *sRandom) GetString(n uint64) string {
result := strings.Builder{}
result.Grow(int(n))
@ -60,13 +60,13 @@ func (p *sCSPRNG) GetString(n uint64) string {
}
// Generate cryptographically strong pseudo-random uint64 number.
func (p *sCSPRNG) GetUint64() uint64 {
func (p *sRandom) GetUint64() uint64 {
res := [encoding.CSizeUint64]byte{}
copy(res[:], p.GetBytes(encoding.CSizeUint64))
return encoding.BytesToUint64(res)
}
// Generate cryptographically strong pseudo-random bool value.
func (p *sCSPRNG) GetBool() bool {
func (p *sRandom) GetBool() bool {
return p.GetBytes(1)[0]%2 == 0
}

View File

@ -8,7 +8,7 @@ import (
func TestCSPRNG(t *testing.T) {
t.Parallel()
r := NewCSPRNG()
r := NewRandom()
if bytes.Equal(r.GetBytes(8), r.GetBytes(8)) {
t.Error("bytes in random equals")
@ -28,7 +28,7 @@ func TestCSPRNG(t *testing.T) {
func TestCSPRNGBool(t *testing.T) {
t.Parallel()
r := NewCSPRNG()
r := NewRandom()
for i := 0; i < 1000; i++ {
t1 := r.GetBool()
t2 := r.GetBool()

View File

@ -1,6 +1,6 @@
package random
type IPRNG interface {
type IRandom interface {
GetString(uint64) string
GetBytes(uint64) []byte
GetUint64() uint64

View File

@ -12,17 +12,17 @@ var (
)
const (
CAESBlockSize = aes.BlockSize
CAESKeySize = 32
CCipherBlockSize = aes.BlockSize
CCipherKeySize = 32
)
type sAESCipher struct {
fBlock cipher.Block
}
func NewAESCipher(pKey []byte) ICipher {
if len(pKey) != CAESKeySize {
panic("len(pKey) != CAESKeySize")
func NewCipher(pKey []byte) ICipher {
if len(pKey) != CCipherKeySize {
panic("len(pKey) != CCipherKeySize")
}
block, _ := aes.NewCipher(pKey)
return &sAESCipher{
@ -32,7 +32,7 @@ func NewAESCipher(pKey []byte) ICipher {
func (p *sAESCipher) EncryptBytes(pMsg []byte) []byte {
blockSize := p.fBlock.BlockSize()
iv := random.NewCSPRNG().GetBytes(uint64(blockSize))
iv := random.NewRandom().GetBytes(uint64(blockSize))
stream := cipher.NewCFBEncrypter(p.fBlock, iv)
result := make([]byte, len(pMsg)+len(iv))

View File

@ -18,7 +18,7 @@ func TestAESKeySize(t *testing.T) {
return
}
}()
_ = NewAESCipher([]byte{123})
_ = NewCipher([]byte{123})
}
func TestAESEncrypt(t *testing.T) {
@ -28,7 +28,7 @@ func TestAESEncrypt(t *testing.T) {
msg = []byte("hello, world!")
)
cipher := NewAESCipher(tgKey)
cipher := NewCipher(tgKey)
emsg := cipher.EncryptBytes(msg)

View File

@ -1,10 +1,6 @@
package symmetric
import (
"github.com/number571/go-peer/pkg/crypto"
)
type ICipher interface {
crypto.IEncrypter
crypto.IDecrypter
EncryptBytes(pMsg []byte) []byte
DecryptBytes(pMsg []byte) []byte
}

View File

@ -1,9 +0,0 @@
package crypto
type IEncrypter interface {
EncryptBytes(pMsg []byte) []byte
}
type IDecrypter interface {
DecryptBytes(pMsg []byte) []byte
}

View File

@ -8,8 +8,8 @@ import (
"time"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/crypto/hashing"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/random"
"github.com/number571/go-peer/pkg/logger"
"github.com/number571/go-peer/pkg/network"
@ -36,7 +36,7 @@ type sNode struct {
fKVDatavase database.IKVDatabase
fNetwork network.INode
fQueue queue.IQBProblemProcessor
fFriends quantum.IListPubKeyChains
fFriends asymmetric.IListPubKeyChains
fHandleRoutes map[uint32]IHandlerF
fHandleActions map[string]chan []byte
}
@ -47,7 +47,7 @@ func NewNode(
pKVDatavase database.IKVDatabase,
pNetwork network.INode,
pQueue queue.IQBProblemProcessor,
pFriends quantum.IListPubKeyChains,
pFriends asymmetric.IListPubKeyChains,
) INode {
return &sNode{
fState: state.NewBoolState(),
@ -102,7 +102,7 @@ func (p *sNode) Run(pCtx context.Context) error {
// update logger state
p.enrichLogger(logBuilder, netMsg).
WithPubKey(p.fQueue.GetClient().GetPrivKeyChain().GetSignerPrivKey().GetPubKey())
WithPubKey(p.fQueue.GetClient().GetPrivKeyChain().GetSignPrivKey().GetPubKey())
// internal logger
_, _ = p.storeHashWithBroadcast(pCtx, logBuilder, netMsg)
@ -131,7 +131,7 @@ func (p *sNode) GetMessageQueue() queue.IQBProblemProcessor {
}
// Return f2f structure.
func (p *sNode) GetListPubKeyChains() quantum.IListPubKeyChains {
func (p *sNode) GetListPubKeyChains() asymmetric.IListPubKeyChains {
return p.fFriends
}
@ -143,7 +143,7 @@ func (p *sNode) HandleFunc(pHead uint32, pHandle IHandlerF) INode {
// Send message without response waiting.
func (p *sNode) SendPayload(
_ context.Context,
pRecv quantum.IKEMPubKey,
pRecv asymmetric.IKEncPubKey,
pPld payload.IPayload64,
) error {
logBuilder := anon_logger.NewLogBuilder(p.fSettings.GetServiceName())
@ -158,10 +158,10 @@ func (p *sNode) SendPayload(
// Payload head must be uint32.
func (p *sNode) FetchPayload(
pCtx context.Context,
pRecv quantum.IKEMPubKey,
pRecv asymmetric.IKEncPubKey,
pPld payload.IPayload32,
) ([]byte, error) {
headAction := sAction(random.NewCSPRNG().GetUint64())
headAction := sAction(random.NewRandom().GetUint64())
actionKey := newActionKey(pRecv, headAction)
p.setAction(actionKey)
@ -263,13 +263,13 @@ func (p *sNode) networkHandler(
}
// do request or response action
return p.handleDoAction(pCtx, logBuilder, keychain.GetKEMPubKey(), pld)
return p.handleDoAction(pCtx, logBuilder, keychain.GetKEncPubKey(), pld)
}
func (p *sNode) handleDoAction(
pCtx context.Context,
pLogBuilder anon_logger.ILogBuilder,
pSender quantum.IKEMPubKey,
pSender asymmetric.IKEncPubKey,
pPld payload.IPayload64,
) error {
// get [head:body] from payload
@ -293,7 +293,7 @@ func (p *sNode) handleDoAction(
func (p *sNode) handleResponse(
_ context.Context,
pLogBuilder anon_logger.ILogBuilder,
pSender quantum.IKEMPubKey,
pSender asymmetric.IKEncPubKey,
pAction iAction,
pBody []byte,
) {
@ -312,7 +312,7 @@ func (p *sNode) handleResponse(
func (p *sNode) handleRequest(
pCtx context.Context,
pLogBuilder anon_logger.ILogBuilder,
pSender quantum.IKEMPubKey,
pSender asymmetric.IKEncPubKey,
pHead iHead,
pBody []byte,
) {
@ -346,7 +346,7 @@ func (p *sNode) handleRequest(
func (p *sNode) enqueuePayload(
pLogBuilder anon_logger.ILogBuilder,
pRecv quantum.IKEMPubKey,
pRecv asymmetric.IKEncPubKey,
pPld payload.IPayload64,
) error {
logType := anon_logger.CLogBaseEnqueueResponse
@ -357,7 +357,7 @@ func (p *sNode) enqueuePayload(
client := p.fQueue.GetClient()
// enrich logger
pLogBuilder.
WithPubKey(client.GetPrivKeyChain().GetSignerPrivKey().GetPubKey()).
WithPubKey(client.GetPrivKeyChain().GetSignPrivKey().GetPubKey()).
WithSize(len(pldBytes))
}
@ -464,7 +464,7 @@ func (p *sNode) delAction(pActionKey string) {
delete(p.fHandleActions, pActionKey)
}
func newActionKey(pPubKey quantum.IKEMPubKey, pAction iAction) string {
pubKeyAddr := hashing.NewSHA256Hasher(pPubKey.ToBytes()).ToBytes()
func newActionKey(pPubKey asymmetric.IKEncPubKey, pAction iAction) string {
pubKeyAddr := hashing.NewHasher(pPubKey.ToBytes()).ToBytes()
return fmt.Sprintf("%s-%d", pubKeyAddr, pAction.uint31())
}

View File

@ -13,7 +13,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/crypto/random"
"github.com/number571/go-peer/pkg/logger"
"github.com/number571/go-peer/pkg/network"
@ -117,7 +117,7 @@ func TestComplexFetchPayload(t *testing.T) {
// nodes[1] -> nodes[0] -> nodes[2]
resp, err := nodes[0].FetchPayload(
ctx,
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload32(testutils.TcHead, []byte(reqBody)),
)
if err != nil {
@ -155,7 +155,7 @@ func TestF2FWithoutFriends(t *testing.T) {
// nodes[1] -> nodes[0] -> nodes[2]
_, err := nodes[0].FetchPayload(
ctx,
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload32(testutils.TcHead, []byte(testutils.TcBody)),
)
if err != nil {
@ -178,7 +178,7 @@ func TestFetchPayload(t *testing.T) {
nodes[1].HandleFunc(
testutils.TcHead,
func(_ context.Context, _ INode, _ quantum.IKEMPubKey, reqBytes []byte) ([]byte, error) {
func(_ context.Context, _ INode, _ asymmetric.IKEncPubKey, reqBytes []byte) ([]byte, error) {
return []byte(fmt.Sprintf("echo: '%s'", string(reqBytes))), nil
},
)
@ -186,7 +186,7 @@ func TestFetchPayload(t *testing.T) {
ctx := context.Background()
_, err := nodes[0].FetchPayload(
ctx,
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload32(testutils.TcHead, []byte(testutils.TcLargeBody)),
)
if err == nil {
@ -196,7 +196,7 @@ func TestFetchPayload(t *testing.T) {
result, err1 := nodes[0].FetchPayload(
ctx,
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload32(testutils.TcHead, []byte(tcMsgBody)),
)
if err1 != nil {
@ -224,7 +224,7 @@ func TestBroadcastPayload(t *testing.T) {
chResult := make(chan string)
nodes[1].HandleFunc(
testutils.TcHead,
func(_ context.Context, _ INode, _ quantum.IKEMPubKey, reqBytes []byte) ([]byte, error) {
func(_ context.Context, _ INode, _ asymmetric.IKEncPubKey, reqBytes []byte) ([]byte, error) {
res := fmt.Sprintf("echo: '%s'", string(reqBytes))
go func() { chResult <- res }()
return nil, nil
@ -233,7 +233,7 @@ func TestBroadcastPayload(t *testing.T) {
err := nodes[0].SendPayload(
context.Background(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload64(uint64(testutils.TcHead), []byte(testutils.TcLargeBody)),
)
if err == nil {
@ -243,7 +243,7 @@ func TestBroadcastPayload(t *testing.T) {
err1 := nodes[0].SendPayload(
context.Background(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload64(uint64(testutils.TcHead), []byte(tcMsgBody)),
)
if err1 != nil {
@ -276,12 +276,12 @@ func TestEnqueuePayload(t *testing.T) {
defer testFreeNodes(nodes[:], cancels[:], 8)
node := nodes[0].(*sNode)
pubKey := nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
pubKey := nodes[1].GetMessageQueue().GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
logBuilder := anon_logger.NewLogBuilder("test")
pld := payload.NewPayload64(uint64(testutils.TcHead), []byte(tcMsgBody))
overheadBody := random.NewCSPRNG().GetBytes(testutils.TCMessageSize + 1)
overheadBody := random.NewRandom().GetBytes(testutils.TCMessageSize + 1)
overPld := payload.NewPayload64(uint64(testutils.TcHead), overheadBody)
if err := node.enqueuePayload(logBuilder, pubKey, overPld); err == nil {
t.Error("success with overhead message")
@ -319,7 +319,7 @@ func TestHandleWrapper(t *testing.T) {
node := _node.(*sNode)
handler := node.networkHandler
client := node.fQueue.GetClient()
pubKey := client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
pubKey := client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
node.GetListPubKeyChains().AddPubKeyChain(client.GetPrivKeyChain().GetPubKeyChain())
@ -365,7 +365,7 @@ func TestHandleWrapper(t *testing.T) {
node.HandleFunc(
111,
func(_ context.Context, _ INode, _ quantum.IKEMPubKey, _ []byte) ([]byte, error) {
func(_ context.Context, _ INode, _ asymmetric.IKEncPubKey, _ []byte) ([]byte, error) {
return nil, errors.New("some error")
},
)
@ -448,7 +448,7 @@ func TestStoreHashWithBroadcastMessage(t *testing.T) {
client := node.fQueue.GetClient()
msg, err := client.EncryptMessage(
client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload64(
joinHead(sAction(1).setType(true), 111).uint64(),
[]byte(tcMsgBody),
@ -513,7 +513,7 @@ func TestRecvSendMessage(t *testing.T) {
}
client := node.fQueue.GetClient()
pubKey := client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
pubKey := client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
actionKey := newActionKey(pubKey, sAction(111).setType(true))
node.setAction(actionKey)
@ -591,7 +591,7 @@ func testNewNodes(t *testing.T, timeWait time.Duration, addresses [2]string, typ
for _, node := range nodes {
node.HandleFunc(
testutils.TcHead,
func(_ context.Context, _ INode, _ quantum.IKEMPubKey, reqBytes []byte) ([]byte, error) {
func(_ context.Context, _ INode, _ asymmetric.IKEncPubKey, reqBytes []byte) ([]byte, error) {
// send response
return []byte(string(reqBytes) + " (response)"), nil
},
@ -722,16 +722,16 @@ func testNewNode(timeWait time.Duration, addr string, typeDB, numDB int) (INode,
client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: testutils.TCMessageSize,
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
),
quantum.NewKEMPrivKey().GetPubKey(),
asymmetric.NewKEncPrivKey().GetPubKey(),
),
quantum.NewListPubKeyChains(),
asymmetric.NewListPubKeyChains(),
)
ctx, cancel := context.WithCancel(context.Background())
go func() { _ = node.Run(ctx) }()

View File

@ -7,7 +7,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/logger"
"github.com/number571/go-peer/pkg/network"
"github.com/number571/go-peer/pkg/network/anonymity"
@ -103,15 +103,15 @@ func newNode(serviceName, address string) anonymity.INode {
client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: msgSize,
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
),
quantum.NewKEMPrivKey().GetPubKey(),
asymmetric.NewKEncPrivKey().GetPubKey(),
),
quantum.NewListPubKeyChains(),
asymmetric.NewListPubKeyChains(),
)
}

View File

@ -5,7 +5,7 @@ import (
"fmt"
"time"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/network/anonymity"
"github.com/number571/go-peer/pkg/payload"
)
@ -44,7 +44,7 @@ func runServiceNode() anonymity.INode {
ctx := context.Background()
node := newNode("snode", nodeAddress).HandleFunc(
nodeRouter,
func(_ context.Context, _ anonymity.INode, _ quantum.IKEMPubKey, b []byte) ([]byte, error) {
func(_ context.Context, _ anonymity.INode, _ asymmetric.IKEncPubKey, b []byte) ([]byte, error) {
return []byte(fmt.Sprintf("echo: %s", string(b))), nil
},
)
@ -56,12 +56,12 @@ func runServiceNode() anonymity.INode {
return node
}
func exchangeKeys(node1, node2 anonymity.INode) (quantum.IKEMPubKey, quantum.IKEMPubKey) {
func exchangeKeys(node1, node2 anonymity.INode) (asymmetric.IKEncPubKey, asymmetric.IKEncPubKey) {
pubKey1 := node1.GetMessageQueue().GetClient().GetPrivKeyChain().GetPubKeyChain()
pubKey2 := node2.GetMessageQueue().GetClient().GetPrivKeyChain().GetPubKeyChain()
node1.GetListPubKeyChains().AddPubKeyChain(pubKey2)
node2.GetListPubKeyChains().AddPubKeyChain(pubKey1)
return pubKey1.GetKEMPubKey(), pubKey2.GetKEMPubKey()
return pubKey1.GetKEncPubKey(), pubKey2.GetKEncPubKey()
}

View File

@ -7,7 +7,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/logger"
"github.com/number571/go-peer/pkg/network"
"github.com/number571/go-peer/pkg/network/anonymity"
@ -103,15 +103,15 @@ func newNode(serviceName, address string) anonymity.INode {
client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: msgSize,
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
),
quantum.NewKEMPrivKey().GetPubKey(),
asymmetric.NewKEncPrivKey().GetPubKey(),
),
quantum.NewListPubKeyChains(),
asymmetric.NewListPubKeyChains(),
)
}

View File

@ -5,7 +5,7 @@ import (
"fmt"
"time"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/encoding"
"github.com/number571/go-peer/pkg/network/anonymity"
"github.com/number571/go-peer/pkg/payload"
@ -17,7 +17,7 @@ const (
)
var (
handler = func(ctx context.Context, n anonymity.INode, pubKey quantum.IKEMPubKey, b []byte) ([]byte, error) {
handler = func(ctx context.Context, n anonymity.INode, pubKey asymmetric.IKEncPubKey, b []byte) ([]byte, error) {
numBytes := [encoding.CSizeUint64]byte{}
copy(numBytes[:], b)
@ -73,12 +73,12 @@ func runServiceNode() anonymity.INode {
return node
}
func exchangeKeys(node1, node2 anonymity.INode) (quantum.IKEMPubKey, quantum.IKEMPubKey) {
func exchangeKeys(node1, node2 anonymity.INode) (asymmetric.IKEncPubKey, asymmetric.IKEncPubKey) {
pubKey1 := node1.GetMessageQueue().GetClient().GetPrivKeyChain().GetPubKeyChain()
pubKey2 := node2.GetMessageQueue().GetClient().GetPrivKeyChain().GetPubKeyChain()
node1.GetListPubKeyChains().AddPubKeyChain(pubKey2)
node2.GetListPubKeyChains().AddPubKeyChain(pubKey1)
return pubKey1.GetKEMPubKey(), pubKey2.GetKEMPubKey()
return pubKey1.GetKEncPubKey(), pubKey2.GetKEncPubKey()
}

View File

@ -1,7 +1,7 @@
package logger
import (
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/network/conn"
)
@ -15,7 +15,7 @@ type sLogBuilder struct {
fHash []byte
fProof uint64
fSize uint64
fPubKey quantum.ISignerPubKey
fPubKey asymmetric.ISignPubKey
fConn conn.IConn
fGetter ILogGetter
@ -48,7 +48,7 @@ func (p *sLogBuilder) WithProof(pProof uint64) ILogBuilder {
return p
}
func (p *sLogBuilder) WithPubKey(pPubKey quantum.ISignerPubKey) ILogBuilder {
func (p *sLogBuilder) WithPubKey(pPubKey asymmetric.ISignPubKey) ILogBuilder {
p.fPubKey = pPubKey
return p
}

View File

@ -1,7 +1,7 @@
package logger
import (
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/network/conn"
)
@ -39,7 +39,7 @@ func (p *sLogGetter) GetSize() uint64 {
return p.fLogBuilder.fSize
}
func (p *sLogGetter) GetPubKey() quantum.ISignerPubKey {
func (p *sLogGetter) GetPubKey() asymmetric.ISignPubKey {
return p.fLogBuilder.fPubKey
}

View File

@ -1,7 +1,7 @@
package logger
import (
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/network/conn"
)
@ -47,7 +47,7 @@ type ILogBuilder interface {
WithProof(uint64) ILogBuilder
WithHash([]byte) ILogBuilder
WithConn(conn.IConn) ILogBuilder
WithPubKey(quantum.ISignerPubKey) ILogBuilder
WithPubKey(asymmetric.ISignPubKey) ILogBuilder
}
type ILogGetterFactory interface {
@ -61,5 +61,5 @@ type ILogGetter interface {
GetProof() uint64
GetHash() []byte
GetConn() conn.IConn
GetPubKey() quantum.ISignerPubKey
GetPubKey() asymmetric.ISignPubKey
}

View File

@ -9,7 +9,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/network/anonymity/queue"
net_message "github.com/number571/go-peer/pkg/network/message"
"github.com/number571/go-peer/pkg/payload"
@ -33,14 +33,14 @@ func main() {
client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: (8 << 10),
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
),
quantum.NewKEMPrivKey().GetPubKey(),
asymmetric.NewKEncPrivKey().GetPubKey(),
)
ctx, cancel := context.WithCancel(context.Background())
@ -54,7 +54,7 @@ func main() {
for i := 0; i < 3; i++ {
err := q.EnqueueMessage(
q.GetClient().GetPrivKeyChain().GetKEMPrivKey().GetPubKey(),
q.GetClient().GetPrivKeyChain().GetKEncPrivKey().GetPubKey(),
payload.NewPayload64(payloadHead, []byte(fmt.Sprintf("hello, world! %d", i))).ToBytes(),
)
if err != nil {
@ -82,7 +82,7 @@ func main() {
if pld.GetHead() != payloadHead {
panic("payload head is invalid")
}
if !bytes.Equal(pubKey.ToBytes(), q.GetClient().GetPrivKeyChain().GetSignerPrivKey().GetPubKey().ToBytes()) {
if !bytes.Equal(pubKey.ToBytes(), q.GetClient().GetPrivKeyChain().GetSignPrivKey().GetPubKey().ToBytes()) {
panic("public key is invalid")
}
fmt.Println(string(pld.GetBody()))

View File

@ -7,7 +7,7 @@ import (
"time"
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/crypto/random"
"github.com/number571/go-peer/pkg/encoding"
"github.com/number571/go-peer/pkg/payload"
@ -40,13 +40,13 @@ type sMainPool struct {
type sRandPool struct {
fCount int64 // atomic variable
fQueue chan net_message.IMessage
fReceiver quantum.IKEMPubKey
fReceiver asymmetric.IKEncPubKey
}
func NewQBProblemProcessor(
pSettings ISettings,
pClient client.IClient,
pReceiver quantum.IKEMPubKey,
pReceiver asymmetric.IKEncPubKey,
) IQBProblemProcessor {
return &sQBProblemProcessor{
fState: state.NewBoolState(),
@ -129,7 +129,7 @@ func (p *sQBProblemProcessor) runMainPoolFiller(pCtx context.Context, pWg *sync.
}
}
func (p *sQBProblemProcessor) EnqueueMessage(pPubKey quantum.IKEMPubKey, pBytes []byte) error {
func (p *sQBProblemProcessor) EnqueueMessage(pPubKey asymmetric.IKEncPubKey, pBytes []byte) error {
incCount := atomic.AddInt64(&p.fMainPool.fCount, 1)
if uint64(incCount) > p.fSettings.GetMainPoolCapacity() {
atomic.AddInt64(&p.fMainPool.fCount, -1)
@ -146,7 +146,7 @@ func (p *sQBProblemProcessor) EnqueueMessage(pPubKey quantum.IKEMPubKey, pBytes
func (p *sQBProblemProcessor) DequeueMessage(pCtx context.Context) net_message.IMessage {
queuePeriod := p.fSettings.GetQueuePeriod()
addRandPeriod := time.Duration(random.NewCSPRNG().GetUint64() % uint64(p.fSettings.GetRandQueuePeriod()+1))
addRandPeriod := time.Duration(random.NewRandom().GetUint64() % uint64(p.fSettings.GetRandQueuePeriod()+1))
for {
select {
@ -207,7 +207,7 @@ func (p *sQBProblemProcessor) fillRandPool(pCtx context.Context) error {
msg, err := p.fClient.EncryptMessage(
p.fRandPool.fReceiver,
random.NewCSPRNG().GetBytes(encoding.CSizeUint64),
random.NewRandom().GetBytes(encoding.CSizeUint64),
)
if err != nil {
panic(err)

View File

@ -11,7 +11,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
net_message "github.com/number571/go-peer/pkg/network/message"
"github.com/number571/go-peer/pkg/payload"
testutils "github.com/number571/go-peer/test/utils"
@ -83,11 +83,11 @@ func TestRunStopQueue(t *testing.T) {
client := client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: testutils.TCMessageSize,
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
)
queue := NewQBProblemProcessor(
@ -100,7 +100,7 @@ func TestRunStopQueue(t *testing.T) {
FQueuePeriod: 100 * time.Millisecond,
}),
client,
quantum.NewKEMPrivKey().GetPubKey(),
asymmetric.NewKEncPrivKey().GetPubKey(),
)
ctx1, cancel1 := context.WithCancel(context.Background())
@ -136,7 +136,7 @@ func TestRunStopQueue(t *testing.T) {
}
}()
pubKey := client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
pubKey := client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
pldBytes := payload.NewPayload64(0, []byte(testutils.TcBody)).ToBytes()
for i := 0; i < testutils.TCQueueCapacity; i++ {
if err := queue.EnqueueMessage(pubKey, pldBytes); err != nil {
@ -174,14 +174,14 @@ func TestQueue(t *testing.T) {
client.NewClient(
message.NewSettings(&message.SSettings{
FMessageSizeBytes: testutils.TCMessageSize,
FEncKeySizeBytes: quantum.CCiphertextSize,
FEncKeySizeBytes: asymmetric.CKEncSize,
}),
quantum.NewPrivKeyChain(
quantum.NewKEMPrivKey(),
quantum.NewSignerPrivKey(),
asymmetric.NewPrivKeyChain(
asymmetric.NewKEncPrivKey(),
asymmetric.NewSignPrivKey(),
),
),
quantum.NewKEMPrivKey().GetPubKey(),
asymmetric.NewKEncPrivKey().GetPubKey(),
)
sett := queue.GetSettings()
@ -210,7 +210,7 @@ func testQueue(queue IQBProblemProcessor) error {
}()
client := queue.GetClient()
pubKey := client.GetPrivKeyChain().GetKEMPrivKey().GetPubKey()
pubKey := client.GetPrivKeyChain().GetKEncPrivKey().GetPubKey()
pldBytes := payload.NewPayload64(0, []byte(testutils.TcBody)).ToBytes()
if err := queue.EnqueueMessage(pubKey, pldBytes); err != nil {
return err

View File

@ -5,7 +5,7 @@ import (
"time"
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/types"
net_message "github.com/number571/go-peer/pkg/network/message"
@ -17,7 +17,7 @@ type IQBProblemProcessor interface {
GetSettings() ISettings
GetClient() client.IClient
EnqueueMessage(quantum.IKEMPubKey, []byte) error
EnqueueMessage(asymmetric.IKEncPubKey, []byte) error
DequeueMessage(context.Context) net_message.IMessage
}

View File

@ -4,7 +4,7 @@ import (
"context"
"time"
"github.com/number571/go-peer/pkg/crypto/quantum"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/logger"
"github.com/number571/go-peer/pkg/network"
"github.com/number571/go-peer/pkg/network/anonymity/queue"
@ -16,7 +16,7 @@ import (
type IHandlerF func(
context.Context,
INode,
quantum.IKEMPubKey,
asymmetric.IKEncPubKey,
[]byte,
) ([]byte, error)
@ -29,10 +29,10 @@ type INode interface {
GetKVDatabase() database.IKVDatabase
GetNetworkNode() network.INode
GetMessageQueue() queue.IQBProblemProcessor
GetListPubKeyChains() quantum.IListPubKeyChains
GetListPubKeyChains() asymmetric.IListPubKeyChains
SendPayload(context.Context, quantum.IKEMPubKey, payload.IPayload64) error
FetchPayload(context.Context, quantum.IKEMPubKey, payload.IPayload32) ([]byte, error)
SendPayload(context.Context, asymmetric.IKEncPubKey, payload.IPayload64) error
FetchPayload(context.Context, asymmetric.IKEncPubKey, payload.IPayload32) ([]byte, error)
}
type ISettings interface {

View File

@ -41,7 +41,7 @@ func (p *tsConn) Read(b []byte) (n int, err error) {
if p.cancelBody {
return 0, errors.New("some error1") // nolint: goerr113
}
bodyBytes := random.NewCSPRNG().GetBytes(p.bodySize)
bodyBytes := random.NewRandom().GetBytes(p.bodySize)
n = copy(b, bodyBytes)
return n, nil
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"github.com/number571/go-peer/pkg/crypto/hashing"
"github.com/number571/go-peer/pkg/crypto/keybuilder"
"github.com/number571/go-peer/pkg/crypto/puzzle"
"github.com/number571/go-peer/pkg/crypto/random"
"github.com/number571/go-peer/pkg/crypto/symmetric"
@ -16,16 +17,16 @@ const (
// IV + Proof + Hash + (2xPayload32Head)=[len(data)+len(void)] + Payload32Head=[head]
// 16 + 8 + 32 + 2x4 + 4 = 68 additional bytes to origin message
CMessageHeadSize = 0 +
1*symmetric.CAESBlockSize +
1*symmetric.CCipherBlockSize +
1*encoding.CSizeUint64 +
1*hashing.CSHA256Size +
1*hashing.CHasherSize +
2*encoding.CSizeUint32 +
1*encoding.CSizeUint32
)
const (
cProofIndex = encoding.CSizeUint64
cHashIndex = cProofIndex + hashing.CSHA256Size
cHashIndex = cProofIndex + hashing.CHasherSize
)
var (
@ -41,19 +42,20 @@ type sMessage struct {
}
func NewMessage(pSett IConstructSettings, pPld payload.IPayload32) IMessage {
prng := random.NewCSPRNG()
prng := random.NewRandom()
sett := pSett.GetSettings()
randBytes := prng.GetBytes(prng.GetUint64() % (pSett.GetRandMessageSizeBytes() + 1))
bytesJoiner := joiner.NewBytesJoiner32([][]byte{pPld.ToBytes(), randBytes})
key := hashing.NewSHA256Hasher([]byte(sett.GetNetworkKey())).ToBytes()
hash := hashing.NewHMACSHA256Hasher(key, bytesJoiner).ToBytes()
keyBuilder := keybuilder.NewKeyBuilder(0, []byte{}) // the network_key must have good entropy
key := keyBuilder.Build(sett.GetNetworkKey(), symmetric.CCipherKeySize)
hash := hashing.NewHMACHasher(key, bytesJoiner).ToBytes()
proof := puzzle.NewPoWPuzzle(sett.GetWorkSizeBits()).ProofBytes(hash, pSett.GetParallel())
proofBytes := encoding.Uint64ToBytes(proof)
cipher := symmetric.NewAESCipher(key)
cipher := symmetric.NewCipher(key)
return &sMessage{
fEncd: cipher.EncryptBytes(bytes.Join(
[][]byte{
@ -86,8 +88,9 @@ func LoadMessage(pSett ISettings, pData interface{}) (IMessage, error) {
return nil, ErrInvalidHeaderSize
}
key := hashing.NewSHA256Hasher([]byte(pSett.GetNetworkKey())).ToBytes()
dBytes := symmetric.NewAESCipher(key).DecryptBytes(msgBytes)
keyBuilder := keybuilder.NewKeyBuilder(0, []byte{}) // the network_key must have good entropy
key := keyBuilder.Build(pSett.GetNetworkKey(), symmetric.CCipherKeySize)
dBytes := symmetric.NewCipher(key).DecryptBytes(msgBytes)
proofArr := [encoding.CSizeUint64]byte{}
copy(proofArr[:], dBytes[:cProofIndex])
@ -104,7 +107,7 @@ func LoadMessage(pSett ISettings, pData interface{}) (IMessage, error) {
return nil, ErrDecodeBytesJoiner
}
newHash := hashing.NewHMACSHA256Hasher(key, dBytes[cHashIndex:]).ToBytes()
newHash := hashing.NewHMACHasher(key, dBytes[cHashIndex:]).ToBytes()
if !bytes.Equal(hash, newHash) {
return nil, ErrInvalidAuthHash
}

View File

@ -5,6 +5,7 @@ import (
"testing"
"github.com/number571/go-peer/pkg/crypto/hashing"
"github.com/number571/go-peer/pkg/crypto/keybuilder"
"github.com/number571/go-peer/pkg/crypto/puzzle"
"github.com/number571/go-peer/pkg/crypto/random"
"github.com/number571/go-peer/pkg/crypto/symmetric"
@ -123,8 +124,9 @@ func TestMessage(t *testing.T) {
[]byte{},
)
key := hashing.NewSHA256Hasher([]byte(tcNetworkKey)).ToBytes()
newHash := hashing.NewHMACSHA256Hasher(key, payloadRandBytes).ToBytes()
keyBuilder := keybuilder.NewKeyBuilder(0, []byte{}) // the network_key must have good entropy
key := keyBuilder.Build(tcNetworkKey, symmetric.CCipherKeySize)
newHash := hashing.NewHMACHasher(key, payloadRandBytes).ToBytes()
if !bytes.Equal(msg.GetHash(), newHash) {
t.Error("payload hash not equal hash of message")
return
@ -209,13 +211,13 @@ func TestMessage(t *testing.T) {
return
}
randBytes := random.NewCSPRNG().GetBytes(encoding.CSizeUint64 + hashing.CSHA256Size)
randBytes := random.NewRandom().GetBytes(encoding.CSizeUint64 + hashing.CHasherSize)
if _, err := LoadMessage(sett.GetSettings(), randBytes); err == nil {
t.Error("success load incorrect message")
return
}
prng := random.NewCSPRNG()
prng := random.NewRandom()
if _, err := LoadMessage(sett.GetSettings(), prng.GetBytes(64)); err == nil {
t.Error("success load incorrect message")
return
@ -224,7 +226,7 @@ func TestMessage(t *testing.T) {
msgBytes := bytes.Join(
[][]byte{
{}, // pass payload
hashing.NewSHA256Hasher([]byte{}).ToBytes(),
hashing.NewHasher([]byte{}).ToBytes(),
},
[]byte{},
)
@ -253,13 +255,14 @@ func tNewInvalidMessage1(pSett IConstructSettings, pPld payload.IPayload32) IMes
bytesJoiner := joiner.NewBytesJoiner32([][]byte{pPld.ToBytes()})
sett := pSett.GetSettings()
key := hashing.NewSHA256Hasher([]byte(sett.GetNetworkKey())).ToBytes()
hash := hashing.NewHMACSHA256Hasher(key, bytesJoiner).ToBytes()
keyBuilder := keybuilder.NewKeyBuilder(0, []byte{}) // the network_key must have good entropy
key := keyBuilder.Build(tcNetworkKey, symmetric.CCipherKeySize)
hash := hashing.NewHMACHasher(key, bytesJoiner).ToBytes()
proof := puzzle.NewPoWPuzzle(sett.GetWorkSizeBits()).ProofBytes(hash, pSett.GetParallel())
proofBytes := encoding.Uint64ToBytes(proof)
cipher := symmetric.NewAESCipher(key)
cipher := symmetric.NewCipher(key)
return &sMessage{
fEncd: cipher.EncryptBytes(bytes.Join(
[][]byte{
@ -276,21 +279,22 @@ func tNewInvalidMessage1(pSett IConstructSettings, pPld payload.IPayload32) IMes
}
func tNewInvalidMessage2(pSett IConstructSettings, pPld payload.IPayload32) IMessage {
prng := random.NewCSPRNG()
prng := random.NewRandom()
sett := pSett.GetSettings()
voidBytes := prng.GetBytes(prng.GetUint64() % (pSett.GetRandMessageSizeBytes() + 1))
bytesJoiner := joiner.NewBytesJoiner32([][]byte{pPld.ToBytes(), voidBytes})
key := hashing.NewSHA256Hasher([]byte(sett.GetNetworkKey())).ToBytes()
hash := hashing.NewHMACSHA256Hasher(key, bytesJoiner).ToBytes()
keyBuilder := keybuilder.NewKeyBuilder(0, []byte{}) // the network_key must have good entropy
key := keyBuilder.Build(tcNetworkKey, symmetric.CCipherKeySize)
hash := hashing.NewHMACHasher(key, bytesJoiner).ToBytes()
hash[0] ^= 1
proof := puzzle.NewPoWPuzzle(sett.GetWorkSizeBits()).ProofBytes(hash, pSett.GetParallel())
proofBytes := encoding.Uint64ToBytes(proof)
cipher := symmetric.NewAESCipher(key)
cipher := symmetric.NewCipher(key)
return &sMessage{
fEncd: cipher.EncryptBytes(bytes.Join(
[][]byte{
@ -308,19 +312,20 @@ func tNewInvalidMessage2(pSett IConstructSettings, pPld payload.IPayload32) IMes
}
func tNewInvalidMessage3(pSett IConstructSettings, pPld payload.IPayload32) IMessage {
prng := random.NewCSPRNG()
prng := random.NewRandom()
sett := pSett.GetSettings()
voidBytes := prng.GetBytes(prng.GetUint64() % (pSett.GetRandMessageSizeBytes() + 1))
bytesJoiner := joiner.NewBytesJoiner32([][]byte{nil, voidBytes})
key := hashing.NewSHA256Hasher([]byte(sett.GetNetworkKey())).ToBytes()
hash := hashing.NewHMACSHA256Hasher(key, bytesJoiner).ToBytes()
keyBuilder := keybuilder.NewKeyBuilder(0, []byte{}) // the network_key must have good entropy
key := keyBuilder.Build(tcNetworkKey, symmetric.CCipherKeySize)
hash := hashing.NewHMACHasher(key, bytesJoiner).ToBytes()
proof := puzzle.NewPoWPuzzle(sett.GetWorkSizeBits()).ProofBytes(hash, pSett.GetParallel())
proofBytes := encoding.Uint64ToBytes(proof)
cipher := symmetric.NewAESCipher(key)
cipher := symmetric.NewCipher(key)
return &sMessage{
fEncd: cipher.EncryptBytes(bytes.Join(
[][]byte{

View File

@ -8,13 +8,13 @@ import (
)
var tgSlice = [][]byte{
random.NewCSPRNG().GetBytes(456),
random.NewRandom().GetBytes(456),
[]byte("hello"),
[]byte("world->571"),
random.NewCSPRNG().GetBytes(571),
random.NewRandom().GetBytes(571),
[]byte("qwerty"),
{},
random.NewCSPRNG().GetBytes(123),
random.NewRandom().GetBytes(123),
{},
}

View File

@ -5,8 +5,6 @@ import (
"fmt"
"os"
"testing"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
)
const (
@ -94,19 +92,19 @@ func TestBasicDB(t *testing.T) {
}
defer store.Close()
secret1 := asymmetric.NewRSAPrivKey(512).ToBytes()
if err := store.Set([]byte("KEY"), secret1); err != nil {
data1 := []byte("hello, world!")
if err := store.Set([]byte("KEY"), data1); err != nil {
t.Error(err)
return
}
secret2, err := store.Get([]byte("KEY"))
data2, err := store.Get([]byte("KEY"))
if err != nil {
t.Error("[testBasic]", err)
return
}
if !bytes.Equal(secret1, secret2) {
if !bytes.Equal(data1, data2) {
t.Error("[testBasic] saved and loaded values not equals")
return
}

View File

@ -44,7 +44,7 @@ func TestTryN(t *testing.T) {
1000,
10*time.Millisecond,
func() error {
if random.NewCSPRNG().GetBool() {
if random.NewRandom().GetBool() {
return errors.New("some error")
}
return nil