R
R
RedSs2019-01-07 16:15:20
go
RedSs, 2019-01-07 16:15:20

How to create a password-protected archive in golang?

How to create a password-protected archive in golang?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rikonardo, 2019-01-07
@RedSs

contents := []byte("Hello World")

// write a password zip
raw := new(bytes.Buffer)
zipw := zip.NewWriter(raw)
w, err := zipw.Encrypt("hello.txt", "golang")
if err != nil {
    log.Fatal(err)
}
_, err = io.Copy(w, bytes.NewReader(contents))
if err != nil {
    log.Fatal(err)
}
zipw.Close()

And this is how you can read the archive with a password [spoiler]
// read the password zip
zipr, err := zip.NewReader(bytes.NewReader(raw.Bytes()), int64(raw.Len()))
if err != nil {
    log.Fatal(err)
}
for _, z := range zipr.File {
    z.SetPassword("golang")
    rr, err := z.Open()
    if err != nil {
        log.Fatal(err)
    }
    _, err = io.Copy(os.Stdout, rr)
    if err != nil {
        log.Fatal(err)
    }
    rr.Close()
}

Creates a .zip archive with hello.txt file and golang password
Taken from official documentation ( from here ).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question