github.com/gagliardetto/solana-go@v1.11.0/vault/passphrase.go (about) 1 // Copyright 2020 dfuse Platform Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package vault 16 17 import ( 18 crypto_rand "crypto/rand" 19 "encoding/base64" 20 "fmt" 21 "io" 22 23 "golang.org/x/crypto/nacl/secretbox" 24 ) 25 26 type PassphraseBoxer struct { 27 passphrase string 28 } 29 30 func NewPassphraseBoxer(password string) *PassphraseBoxer { 31 return &PassphraseBoxer{ 32 passphrase: password, 33 } 34 } 35 36 func (b *PassphraseBoxer) WrapType() string { 37 return "passphrase" 38 } 39 40 func (b *PassphraseBoxer) Seal(in []byte) (string, error) { 41 var nonce [nonceLength]byte 42 if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil { 43 return "", err 44 } 45 46 salt := make([]byte, saltLength) 47 if _, err := io.ReadFull(crypto_rand.Reader, salt); err != nil { 48 return "", err 49 } 50 secretKey := deriveKey(b.passphrase, salt) 51 prefix := append(salt, nonce[:]...) 52 53 cipherText := secretbox.Seal(prefix, in, &nonce, &secretKey) 54 55 return base64.RawStdEncoding.EncodeToString(cipherText), nil 56 } 57 58 func (b *PassphraseBoxer) Open(in string) ([]byte, error) { 59 buf, err := base64.RawStdEncoding.DecodeString(in) 60 if err != nil { 61 return []byte{}, err 62 } 63 64 salt := make([]byte, saltLength) 65 copy(salt, buf[:saltLength]) 66 var nonce [nonceLength]byte 67 copy(nonce[:], buf[saltLength:nonceLength+saltLength]) 68 69 secretKey := deriveKey(b.passphrase, salt) 70 decrypted, ok := secretbox.Open(nil, buf[nonceLength+saltLength:], &nonce, &secretKey) 71 if !ok { 72 return []byte{}, fmt.Errorf("failed to decrypt") 73 } 74 return decrypted, nil 75 }