github.com/piotrnar/gocoin@v0.0.0-20240512203912-faa0448c5e96/wallet/encrypt.go (about)

     1  package main
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"crypto/rand"
     7  	"io"
     8  	"io/ioutil"
     9  	"strings"
    10  )
    11  
    12  func encrypt_file(fn string, key []byte) (outfn string) {
    13  	dat, er := ioutil.ReadFile(fn)
    14  	if er != nil {
    15  		println(er.Error())
    16  		cleanExit(1)
    17  	}
    18  
    19  	cphr, er := aes.NewCipher(key)
    20  	if er != nil {
    21  		println(er.Error())
    22  		cleanExit(1)
    23  	}
    24  
    25  	gcm, er := cipher.NewGCM(cphr)
    26  	if er != nil {
    27  		println(er.Error())
    28  		cleanExit(1)
    29  	}
    30  
    31  	nonce := make([]byte, gcm.NonceSize())
    32  	if _, er = io.ReadFull(rand.Reader, nonce); er != nil {
    33  		println(er.Error())
    34  		cleanExit(1)
    35  	}
    36  
    37  	outfn = fn + ".enc"
    38  
    39  	if er = ioutil.WriteFile(outfn, gcm.Seal(nonce, nonce, dat, nil), 0600); er != nil {
    40  		println(er.Error())
    41  		cleanExit(1)
    42  	}
    43  
    44  	return
    45  }
    46  
    47  func decrypt_file(fn string, key []byte) (outfn string) {
    48  	ciphertext, er := ioutil.ReadFile(fn)
    49  	if er != nil {
    50  		println(er.Error())
    51  		cleanExit(1)
    52  	}
    53  
    54  	cphr, er := aes.NewCipher(key)
    55  	if er != nil {
    56  		println(er.Error())
    57  		cleanExit(1)
    58  	}
    59  
    60  	gcmDecrypt, er := cipher.NewGCM(cphr)
    61  	if er != nil {
    62  		println(er.Error())
    63  		cleanExit(1)
    64  	}
    65  
    66  	nonceSize := gcmDecrypt.NonceSize()
    67  	if len(ciphertext) < nonceSize {
    68  		println("ERROR: Encrypted message is shorter than the nonce size")
    69  		cleanExit(1)
    70  	}
    71  	nonce, encryptedMessage := ciphertext[:nonceSize], ciphertext[nonceSize:]
    72  	plaintext, er := gcmDecrypt.Open(nil, nonce, encryptedMessage, nil)
    73  	if er != nil {
    74  		println(er.Error())
    75  		cleanExit(1)
    76  	}
    77  
    78  	if strings.HasSuffix(fn, ".enc") {
    79  		if len(fn) <= 4 {
    80  			outfn = "out.tmp"
    81  		} else {
    82  			outfn = fn[:len(fn)-4]
    83  		}
    84  	} else {
    85  		outfn = fn + ".dec"
    86  	}
    87  
    88  	if er = ioutil.WriteFile(outfn, plaintext, 0600); er != nil {
    89  		println(er.Error())
    90  		cleanExit(1)
    91  	}
    92  
    93  	return
    94  }