Created
December 30, 2017 20:33
-
-
Save eginez/744e7eecb732e0222a12c9875177662c to your computer and use it in GitHub Desktop.
playing with go crypto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/sha1" | |
"crypto/x509" | |
"encoding/hex" | |
"encoding/pem" | |
"fmt" | |
"golang.org/x/crypto/pbkdf2" | |
) | |
// How to share a message securely with multiple agents | |
// Eeach agent create a public/private key pair | |
// An key K is created | |
// The message gets encrypted with K | |
// K gets encrypted with all public keys | |
// The recipt recieves the message and the encrypted Ks | |
// The recepeit tries to decrypt K with is private key | |
//Once decrypted it usses the key to decrypt the message | |
type KeyPair interface { | |
Keys() (string, string) | |
} | |
type Concealer interface { | |
Setup() error | |
Encrypt(msg []byte) ([]byte, error) | |
Decrypt(msg []byte) ([]byte, error) | |
AsString() (string, string) | |
} | |
type RSAConcealer struct { | |
PrivateKey *rsa.PrivateKey | |
PublicKey *rsa.PublicKey | |
} | |
func (r *RSAConcealer) Setup() (err error) { | |
r.PrivateKey, err = rsa.GenerateKey(rand.Reader, 2048) | |
r.PublicKey = &r.PrivateKey.PublicKey | |
return | |
} | |
func (r *RSAConcealer) AsString() (string, string) { | |
pemEncoded := pem.EncodeToMemory(&pem.Block{ | |
Type: "PRIVATE KEY", | |
Bytes: x509.MarshalPKCS1PrivateKey(r.PrivateKey), | |
}) | |
bs, _ := x509.MarshalPKIXPublicKey(r.PublicKey) | |
publicPem := pem.EncodeToMemory(&pem.Block{ | |
Type: "PUBLIC KEY", | |
Bytes: bs, | |
}) | |
return string(pemEncoded), string(publicPem) | |
} | |
func (r *RSAConcealer) Encrypt(msg []byte) (enc []byte, err error) { | |
return rsa.EncryptPKCS1v15(rand.Reader, r.PublicKey, msg) | |
} | |
func (r *RSAConcealer) Decrypt(msg []byte) (enc []byte, err error) { | |
return rsa.DecryptPKCS1v15(rand.Reader, r.PrivateKey, msg) | |
} | |
func main() { | |
r := RSAConcealer{} | |
r.Setup() | |
//fmt.Println(r.AsString()) | |
enc, _ := r.Encrypt([]byte("some message")) | |
dec, _ := r.Decrypt(enc) | |
fmt.Println(string(dec)) | |
//Deriving a key from a password | |
salt := make([]byte, 8) | |
rand.Reader.Read(salt) | |
key := pbkdf2.Key([]byte("the password"), salt, 2048, 32, sha1.New) | |
fmt.Println(hex.EncodeToString(key)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment