I need help creating a zip file and protecting it with a password. I am creating the zip files using the standard package, but it does not provide any protection.
9 Years Repo! OK Thank you.
why the the golang Project dose add this to the standard Package? why you thing
In Go, there’s a common philosophy of separation of concerns. Tasks like compression and encryption are seen as distinct functionalities:
- Compression is about reducing file size.
- Encryption is about protecting data confidentiality.
You can just wrap the standard library with encryption yourself. There are tons of simple examples, how to use crypto
package in addition to zip
.
Something like:
import (
"archive/zip"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"os"
)
// Generate a random AES key of the given size (32 bytes for AES-256)
func generateKey() ([]byte, error) {
key := make([]byte, 32) // 32 bytes for AES-256
_, err := rand.Read(key)
if err != nil {
return nil, err
}
return key, nil
}
// Encrypt the content using AES-GCM
func encrypt(content []byte, key []byte) ([]byte, []byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, nil, err
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, nil, err
}
ciphertext := gcm.Seal(nonce, nonce, content, nil)
return ciphertext, nonce, nil
}
// Add an encrypted file to the zip archive
func addEncryptedFileToZip(zipWriter *zip.Writer, filename string, key []byte) error {
file, err := os.ReadFile(filename)
if err != nil {
return err
}
encryptedContent, _, err := encrypt(file, key)
if err != nil {
return err
}
zipFileWriter, err := zipWriter.Create(filename)
if err != nil {
return err
}
_, err = zipFileWriter.Write(encryptedContent)
if err != nil {
return err
}
return nil
}
In most environments I’d say use ccrypt or something similar if you want to encrypt your data. IIRC the standards for encrypted zip files are all over the place with a popular one being WinZip’s AES encryption. If you want to read more about why it’s not in the stdlib, here you go:
Go’s stdlib is the most capable I’ve used (in most other ecosystems, you probably wouldn’t get archive/zip
out of the box). I think relying on the OS community for non-standard stuff like WinZip AES encryption is smart.