mirror of https://github.com/schollz/croc.git
add messaging
This commit is contained in:
parent
a7f12ca179
commit
6b149480d4
|
@ -0,0 +1,40 @@
|
||||||
|
package message
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/schollz/croc/v6/src/compress"
|
||||||
|
"github.com/schollz/croc/v6/src/crypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
Type string `json:"t,omitempty"`
|
||||||
|
Message string `json:"m,omitempty"`
|
||||||
|
Bytes []byte `json:"b,omitempty"`
|
||||||
|
Num int `json:"n,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Encode(m Message, e ...crypt.Encryption) (b []byte, err error) {
|
||||||
|
b, err = json.Marshal(m)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
b = compress.Compress(b)
|
||||||
|
if len(e) > 0 {
|
||||||
|
b, err = e[0].Encrypt(b)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func Decode(b []byte, e ...crypt.Encryption) (m Message, err error) {
|
||||||
|
if len(e) > 0 {
|
||||||
|
b, err = e[0].Decrypt(b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b = compress.Decompress(b)
|
||||||
|
err = json.Unmarshal(b, &m)
|
||||||
|
return
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package message
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/schollz/croc/v6/src/crypt"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMessage(t *testing.T) {
|
||||||
|
m := Message{Type: "message", Message: "hello, world"}
|
||||||
|
e, err := crypt.New([]byte("passphrase"), nil)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
fmt.Println(e.Salt())
|
||||||
|
b, err := Encode(m, e)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
fmt.Printf("%x\n", b)
|
||||||
|
|
||||||
|
m2, err := Decode(b, e)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, m, m2)
|
||||||
|
}
|
Loading…
Reference in New Issue