W Khan
W Khan

Reputation: 53

Golang file encryption with crypto/aes lib

I am trying to encrypt a file using the Go crypto/aes package. I have so far:

func encrypt(source string, localdir string) error {

    src := filepath.Join("/home/bacula/cloud-backup/"+localdir, source)
    dst := filepath.Join(src + ".aes")

    fmt.Println(src)
    fmt.Println(dst)
    key := []byte("example key 1234")

    iv := []byte(key)[:aes.BlockSize]

    aesBlockEncrypter, err := aes.NewCipher([]byte(key))
    if err != nil {
            return err
    }
    aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
    aesEncrypter.XORKeyStream([]byte(dst), []byte(src))
    return nil
}

My first question is, how can I improve the way I am generating the IV? And secondly, there is no output file, so how do I stream the file through XORKeyStream?

Upvotes: 4

Views: 14435

Answers (1)

holys
holys

Reputation: 14809

There is an example in the crypto/cipher package documentation.

I've tweaked the example to make new example for you:

func main() {
    // read content from your file
    plaintext, err := ioutil.ReadFile("you_file_to_be_encrypted")
    if err != nil {
        panic(err.Error())
    }

    // this is a key
    key := []byte("example key 1234")

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // The IV needs to be unique, but not secure. Therefore it's common to
    // include it at the beginning of the ciphertext.
    ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

    // create a new file for saving the encrypted data.
    f, err := os.Create("a_aes.txt")
    if err != nil {
        panic(err.Error())
    }
    _, err = io.Copy(f, bytes.NewReader(ciphertext))
    if err != nil {
        panic(err.Error())
    }

    // done
}

Upvotes: 13

Related Questions