Skip to content

Instantly share code, notes, and snippets.

@bongtrop
Last active September 6, 2021 07:02
Show Gist options
  • Save bongtrop/68f27b4a16048d7ecd24d83d1b0e64da to your computer and use it in GitHub Desktop.
Save bongtrop/68f27b4a16048d7ecd24d83d1b0e64da to your computer and use it in GitHub Desktop.
package main
import (
b64 "encoding/base64"
"fmt"
"github.com/GoKillers/libsodium-go/cryptobox"
)
func main() {
// [server] Generate key pair
serverSk, serverPk, _ := cryptobox.CryptoBoxKeyPair()
// [mobile] Generate key pair
clientSk, clientPk, _ := cryptobox.CryptoBoxKeyPair()
// [mobile] Send clientPk to server
// [server] Send serverPk to client
// [server] Calculate shared key
sharedKeyServer, _ := cryptobox.CryptoBoxBeforeNm(clientPk, serverSk)
sharedKeyServerB64 := b64.StdEncoding.EncodeToString(sharedKeyServer)
// [mobile] Calculate shared key
sharedKeyClient, _ := cryptobox.CryptoBoxBeforeNm(serverPk, clientSk)
sharedKeyClientB64 := b64.StdEncoding.EncodeToString(sharedKeyClient)
// Check that shareKey in mobile and server must be equal
if sharedKeyServerB64 != sharedKeyClientB64 {
panic("Key exchange fail")
}
fmt.Println("Server Shared Key: " + sharedKeyServerB64)
fmt.Println("Mobile Shared Key: " + sharedKeyClientB64)
// To encrypt and decrypt, the CryptoBoxAfterNm() and CryptoBoxOpenAfterNm() functions can be used
// Please see: https://github.com/GoKillers/libsodium-go/blob/master/cryptobox/crypto_box.go#L111-L137
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment