github.com/deroproject/derosuite@v2.1.6-1.0.20200307070847-0f2e589c7a2b+incompatible/walletapi/cipher.go (about)

     1  package walletapi
     2  
     3  import "fmt"
     4  import "crypto/rand"
     5  
     6  import "golang.org/x/crypto/chacha20poly1305"
     7  
     8  // all data in encrypted within the storage using this, PERIOD
     9  // all data has a new nonce, appended to the the data , last 12 bytes
    10  func EncryptWithKey(Key []byte, Data []byte) (result []byte, err error) {
    11  	nonce := make([]byte, chacha20poly1305.NonceSize, chacha20poly1305.NonceSize)
    12  	cipher, err := chacha20poly1305.New(Key)
    13  	if err != nil {
    14  		return
    15  	}
    16  
    17  	_, err = rand.Read(nonce)
    18  	if err != nil {
    19  		return
    20  	}
    21  	Data = cipher.Seal(Data[:0], nonce, Data, nil) // is this okay
    22  
    23  	result = append(Data, nonce...) // append nonce
    24  	return
    25  }
    26  
    27  // extract 12 byte nonce from the data and deseal the data
    28  func DecryptWithKey(Key []byte, Data []byte) (result []byte, err error) {
    29  
    30  	// make sure data is atleast 28 byte, 16 bytes of AEAD cipher and 12 bytes of nonce
    31  	if len(Data) < 28 {
    32  		err = fmt.Errorf("Invalid data")
    33  		return
    34  	}
    35  
    36  	data_without_nonce := Data[0 : len(Data)-chacha20poly1305.NonceSize]
    37  
    38  	nonce := Data[len(Data)-chacha20poly1305.NonceSize:]
    39  
    40  	cipher, err := chacha20poly1305.New(Key)
    41  	if err != nil {
    42  		return
    43  	}
    44  
    45  	return cipher.Open(result[:0], nonce, data_without_nonce, nil) // result buffer should be different
    46  
    47  }
    48  
    49  // use master keys, everytime required
    50  func (w *Wallet) Encrypt(Data []byte) (result []byte, err error) {
    51  	return EncryptWithKey(w.master_password, Data)
    52  }
    53  
    54  // use master keys, everytime required
    55  func (w *Wallet) Decrypt(Data []byte) (result []byte, err error) {
    56  	return DecryptWithKey(w.master_password, Data)
    57  }