zip

package module
v1.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2025 License: MIT Imports: 22 Imported by: 0

README

zip-xxh3

yeka/zip is a fork of Go's archive/zip that adds support for Standard Zip Encryption. This is a fork of yeka/zip that:

  • supports specifying compression level.
  • replaces compress/flate with klauspost/compress/flate which is an optimised version of compress/flate, and implements better gradient accross different compression levels.
  • adds support for XXH3 64 bit checksum (using zeebo/xxh3).

XXhash3 is a extremely fast, non-cryptographic hash function. It is designed to be used in high-performance applications where speed is important. It has excellent collision distribution. XXhash3 is so fast that it is often bottlenecked by how fast you can read bytes off the disk and not the algorithm itself.

Installation

go get github.com/abyii/zip-xxh3

Usage

this package maintains a similar API to the standard archive/zip library but extends it with encryption capabilities via the Create method.

Create function

You can add files to the archive using the Create method on a zip.Writer.

func (w *Writer) Create(name string, method uint16, level int, enc EncryptionMethod, password string) (io.Writer, error)

Arguments:

  • name: The name of the file within the zip archive (e.g., "my_file.txt").
  • method: The compression method to use.
    • zip.Store: No compression.
    • zip.Deflate: Compresses the file data.
  • level: The compression level for the Deflate method. It ranges from -1 (default) to 9 (best compression). For zip.Store, this should be 0.
  • enc: The encryption method.
    • zip.NoEncryption: No encryption.
    • zip.StandardEncryption: Standard Zip 2.0 encryption.
    • zip.AES128Encryption: AES-128 encryption.
    • zip.AES192Encryption: AES-192 encryption.
    • zip.AES256Encryption: AES-256 encryption.
  • password: The password to use for encryption. This is required if an encryption method other than NoEncryption is chosen.

Example:

This example shows how to create a zip file with one compressed and encrypted file.

package main

import (
	"bytes"
	"io"
	"log"
	"os"

	"github.com/abyii/zip-xxh3"
)

func main() {
	// Create a buffer to write our archive to.
	buf := new(bytes.Buffer)

	// Create a new zip archive.
	zipWriter := zip.NewWriter(buf)

	// Add a file to the archive.
	// The file will be named "hello.txt", compressed with Deflate,
	// and encrypted with AES-256.
	writer, err := zipWriter.Create("hello.txt", zip.Deflate, -1, zip.AES256Encryption, "supersecret")
	if err != nil {
		log.Fatal(err)
	}

	// Write content to the file.
	_, err = io.WriteString(writer, "Hello, World!")
	if err != nil {
		log.Fatal(err)
	}

	// Close the zip writer to finalize the archive.
	err = zipWriter.Close()
	if err != nil {
		log.Fatal(err)
	}

	// Write the resulting zip file to disk.
	err = os.WriteFile("encrypted.zip", buf.Bytes(), 0644)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Created encrypted.zip")
}

Detached Mode

Detached mode allows you to create a zip file from parts that can be processed concurrently. This is useful when you need to generate file parts in parallel and then assemble them into a single zip archive at the end. The process involves creating individual file parts, generating a central directory, and then appending all the pieces together.

Functions:

  • CreateFilePartSimple(name string, method uint16, level int, enc EncryptionMethod, password string, order int, partWriter io.Writer) (io.WriteCloser, error): Creates a new file part in the zip archive. It returns a writer to which the file contents should be written.
  • GetCentralDirectoryBytes() ([]byte, error): Returns the central directory for the zip archive. This should be called after all file parts have been created and closed.

Example:

This example demonstrates how to create a zip file with multiple file parts, including one that is encrypted. The file parts are created in memory and then assembled into a final zip file.

package main

import (
	"bytes"
	"io"
	"log"
	"os"

	"github.com/abyii/zip-xxh3"
)

func main() {
	// Create a new detached writer.
	zipw := zip.NewWriter()

	// Define the files to be added to the zip archive.
	testFiles := []struct {
		Name     string
		Content  []byte
		Password string
	}{
		{"hello.txt", []byte("Hello, World!"), ""},
		{"secret.txt", []byte("This is a secret."), "supersecret"},
	}

	// Create file parts and write content.
	var fileParts [][]byte
	for i, tf := range testFiles {
		buf := new(bytes.Buffer)
		encMethod := zip.NoEncryption
		if tf.Password != "" {
			encMethod = zip.AES256Encryption
		}
		w, err := zipw.CreateFilePartSimple(tf.Name, zip.Deflate, -1, encMethod, tf.Password, i, buf)
		if err != nil {
			log.Fatalf("Failed to create file part for %s: %v", tf.Name, err)
		}
		_, err = w.Write(tf.Content)
		if err != nil {
			log.Fatalf("Failed to write to file part for %s: %v", tf.Name, err)
		}
		if err := w.Close(); err != nil {
			log.Fatalf("Failed to close file part for %s: %v", tf.Name, err)
		}
		fileParts = append(fileParts, buf.Bytes())
	}

	// Get the central directory.
	cd, err := zipw.GetCentralDirectoryBytes()
	if err != nil {
		log.Fatalf("Failed to get central directory: %v", err)
	}

	// Assemble the zip file.
	var finalZip bytes.Buffer
	for _, part := range fileParts {
		finalZip.Write(part)
	}
	finalZip.Write(cd)

	// Write the resulting zip file to disk.
	err = os.WriteFile("detached.zip", finalZip.Bytes(), 0644)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Created detached.zip")
}

Documentation

Overview

Package zip provides support for reading and writing password protected ZIP archives.

See: http://www.pkware.com/documents/casestudies/APPNOTE.TXT

This package does not support disk spanning.

A note about ZIP64:

To be backwards compatible the FileHeader has both 32 and 64 bit Size fields. The 64 bit fields will always contain the correct value and for normal archives both fields will be the same. For files requiring the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit fields must be used instead.

Can read/write password protected files that use Winzip's AES encryption method. See: http://www.winzip.com/aes_info.htm

Index

Examples

Constants

View Source
const (
	Store   uint16 = 0
	Deflate uint16 = 8
)

Compression methods.

Variables

View Source
var (
	ErrDecryption     = errors.New("zip: decryption error")
	ErrPassword       = errors.New("zip: invalid password")
	ErrAuthentication = errors.New("zip: authentication failed")
)

Encryption/Decryption Errors

View Source
var (
	ErrFormat    = errors.New("zip: not a valid zip file")
	ErrAlgorithm = errors.New("zip: unsupported compression algorithm")
	ErrChecksum  = errors.New("zip: checksum error")
	ErrXXH3      = errors.New("zip: xxh3 checksum error")
)

Functions

func RegisterCompressor

func RegisterCompressor(method uint16, comp Compressor)

RegisterCompressor registers custom compressors for a specified method ID. The common methods Store and Deflate are built in.

func RegisterDecompressor

func RegisterDecompressor(method uint16, d Decompressor)

RegisterDecompressor allows custom decompressors for a specified method ID.

func ZipCryptoDecryptor

func ZipCryptoDecryptor(r *io.SectionReader, password []byte) (*io.SectionReader, error)

func ZipCryptoEncryptor

func ZipCryptoEncryptor(i io.Writer, pass passwordFn, fw *fileWriter) (io.Writer, error)

Types

type Compressor

type Compressor func(io.Writer) (io.WriteCloser, error)

A Compressor returns a compressing writer, writing to the provided writer. On Close, any pending data should be flushed.

type Decompressor

type Decompressor func(io.Reader) io.ReadCloser

Decompressor is a function that wraps a Reader with a decompressing Reader. The decompressed ReadCloser is returned to callers who open files from within the archive. These callers are responsible for closing this reader when they're finished reading.

type EncryptionMethod

type EncryptionMethod int
const (
	NoEncryption       EncryptionMethod = 0
	StandardEncryption EncryptionMethod = 1
	AES128Encryption   EncryptionMethod = 2
	AES192Encryption   EncryptionMethod = 3
	AES256Encryption   EncryptionMethod = 4
)

type File

type File struct {
	FileHeader
	// contains filtered or unexported fields
}

func (*File) DataOffset

func (f *File) DataOffset() (offset int64, err error)

DataOffset returns the offset of the file's possibly-compressed data, relative to the beginning of the zip file.

Most callers should instead use Open, which transparently decompresses data and verifies checksums.

func (*File) Open

func (f *File) Open() (rc io.ReadCloser, err error)

Open returns a ReadCloser that provides access to the File's contents. Multiple files may be read concurrently.

func (*File) VerifyXXH3

func (f *File) VerifyXXH3() error

type FileHeader

type FileHeader struct {
	// Name is the name of the file.
	// It must be a relative path: it must not start with a drive
	// letter (e.g. C:) or leading slash, and only forward slashes
	// are allowed.
	Name string

	CreatorVersion uint16
	ReaderVersion  uint16
	Flags          uint16
	Method         uint16 // Compression method used to compress the file.

	// CompressionLevel is the compression level to use.
	// This is only valid for Deflate compression.
	// -1 means default compression level (5),
	// 0 means no compression,
	// 1 means best speed compression,
	// 9 means best compression.
	CompressionLevel int

	ModifiedTime       uint16 // MS-DOS time
	ModifiedDate       uint16 // MS-DOS date
	CRC32              uint32
	CompressedSize     uint32 // Deprecated: Use CompressedSize64 instead.
	UncompressedSize   uint32 // Deprecated: Use UncompressedSize64 instead.
	CompressedSize64   uint64
	UncompressedSize64 uint64
	Extra              []byte
	ExternalAttrs      uint32 // Meaning depends on CreatorVersion
	Comment            string
	XXH3               uint64

	// DeferAuth being set to true will delay hmac auth/integrity
	// checks when decrypting a file meaning the reader will be
	// getting unauthenticated plaintext. It is recommended to leave
	// this set to false. For more detail:
	// https://www.imperialviolet.org/2014/06/27/streamingencryption.html
	// https://www.imperialviolet.org/2015/05/16/aeads.html
	DeferAuth bool
	// contains filtered or unexported fields
}

FileHeader describes a file within a zip file. See the zip spec for details.

func FileInfoHeader

func FileInfoHeader(fi os.FileInfo) (*FileHeader, error)

FileInfoHeader creates a partially-populated FileHeader from an os.FileInfo. Because os.FileInfo's Name method returns only the base name of the file it describes, it may be necessary to modify the Name field of the returned header to provide the full path name of the file.

func (*FileHeader) FileInfo

func (h *FileHeader) FileInfo() os.FileInfo

FileInfo returns an os.FileInfo for the FileHeader.

func (*FileHeader) IsEncrypted

func (h *FileHeader) IsEncrypted() bool

IsEncrypted indicates whether this file's data is encrypted.

func (*FileHeader) ModTime

func (h *FileHeader) ModTime() time.Time

ModTime returns the modification time in UTC. The resolution is 2s.

func (*FileHeader) Mode

func (h *FileHeader) Mode() (mode os.FileMode)

Mode returns the permission and mode bits for the FileHeader.

func (*FileHeader) SetEncryptionMethod

func (h *FileHeader) SetEncryptionMethod(enc EncryptionMethod)

SetEncryptionMethod sets the encryption method.

func (*FileHeader) SetModTime

func (h *FileHeader) SetModTime(t time.Time)

SetModTime sets the ModifiedTime and ModifiedDate fields to the given time in UTC. The resolution is 2s.

func (*FileHeader) SetMode

func (h *FileHeader) SetMode(mode os.FileMode)

SetMode changes the permission and mode bits for the FileHeader.

func (*FileHeader) SetPassword

func (h *FileHeader) SetPassword(password string)

SetPassword sets the password used for encryption/decryption.

type ReadCloser

type ReadCloser struct {
	Reader
	// contains filtered or unexported fields
}

func OpenReader

func OpenReader(name string) (*ReadCloser, error)

OpenReader will open the Zip file specified by name and return a ReadCloser.

func (*ReadCloser) Close

func (rc *ReadCloser) Close() error

Close closes the Zip file, rendering it unusable for I/O.

type Reader

type Reader struct {
	File    []*File
	Comment string
	// contains filtered or unexported fields
}
Example
package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"github.com/yeka/zip"
)

func main() {
	// Open a zip archive for reading.
	r, err := zip.OpenReader("testdata/readme.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	// Iterate through the files in the archive,
	// printing some of their contents.
	for _, f := range r.File {
		fmt.Printf("Contents of %s:\n", f.Name)
		rc, err := f.Open()
		if err != nil {
			log.Fatal(err)
		}
		_, err = io.CopyN(os.Stdout, rc, 68)
		if err != nil {
			log.Fatal(err)
		}
		rc.Close()
		fmt.Println()
	}
}
Output:

Contents of README:
This is the source code repository for the Go programming language.

func NewReader

func NewReader(r io.ReaderAt, size int64) (*Reader, error)

NewReader returns a new Reader reading from r, which is assumed to have the given size in bytes.

func (*Reader) SetPassword added in v1.7.0

func (r *Reader) SetPassword(password string)

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer implements a zip file writer.

Example
package main

import (
	"bytes"
	"log"

	"github.com/yeka/zip"
)

func main() {
	// Create a buffer to write our archive to.
	buf := new(bytes.Buffer)

	// Create a new zip archive.
	w := zip.NewWriter(buf)

	// Add some files to the archive.
	var files = []struct {
		Name, Body string
	}{
		{"readme.txt", "This archive contains some text files."},
		{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
		{"todo.txt", "Get animal handling licence.\nWrite more examples."},
	}
	for _, file := range files {
		f, err := w.Create(file.Name)
		if err != nil {
			log.Fatal(err)
		}
		_, err = f.Write([]byte(file.Body))
		if err != nil {
			log.Fatal(err)
		}
	}

	// Make sure to check the error on Close.
	err := w.Close()
	if err != nil {
		log.Fatal(err)
	}
}

func NewWriter

func NewWriter(w ...io.Writer) *Writer

NewWriter returns a new Writer writing a zip file to w.

func (*Writer) Close

func (w *Writer) Close() error

Close finishes writing the zip file by writing the central directory. It does not (and can not) close the underlying writer.

func (*Writer) Create

func (w *Writer) Create(name string, method uint16, level int, enc EncryptionMethod, password string) (io.Writer, error)

Create adds a file to the zip file using the provided name, compression and encryption options. It returns a Writer to which the file contents should be written. The name must be a relative path: it must not start with a drive letter (e.g. C:) or leading slash, and only forward slashes are allowed. The file's contents must be written to the io.Writer before the next call to Create, CreateHeader, or Close.

func (*Writer) CreateFilePartSimple added in v1.6.0

func (w *Writer) CreateFilePartSimple(name string, method uint16, level int, enc EncryptionMethod, password string, order int, partWriter io.Writer) (io.WriteCloser, error)

CreateFilePartSimple adds a file to the zip file using the provided name, compression and encryption options. It returns a Writer to which the file contents should be written. This is for detached mode.

func (*Writer) CreateFileParts added in v1.6.0

func (w *Writer) CreateFileParts(fh *FileHeader, order int, partWriter io.Writer) (io.WriteCloser, error)

func (*Writer) CreateHeader

func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)

CreateHeader adds a file to the zip file using the provided FileHeader for the file metadata. It returns a Writer to which the file contents should be written.

The file's contents must be written to the io.Writer before the next call to Create, CreateHeader, or Close. The provided FileHeader fh must not be modified after a call to CreateHeader.

func (*Writer) Flush

func (w *Writer) Flush() error

Flush flushes any buffered data to the underlying writer. Calling Flush is not normally necessary; calling Close is sufficient.

func (*Writer) GetCentralDirectoryBytes added in v1.6.0

func (w *Writer) GetCentralDirectoryBytes() ([]byte, error)

func (*Writer) SetOffset

func (w *Writer) SetOffset(n int64)

SetOffset sets the offset of the beginning of the zip data within the underlying writer. It should be used when the zip data is appended to an existing file, such as a binary executable. It must be called before any data is written.

type ZipCrypto

type ZipCrypto struct {
	Keys [3]uint32
	// contains filtered or unexported fields
}

func NewZipCrypto

func NewZipCrypto(passphrase []byte) *ZipCrypto

func (*ZipCrypto) Decrypt

func (z *ZipCrypto) Decrypt(chiper []byte) []byte

func (*ZipCrypto) Encrypt

func (z *ZipCrypto) Encrypt(data []byte) []byte

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL