zip

package module
v0.0.16 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2025 License: MIT Imports: 22 Imported by: 0

README

This fork add support for Standard Zip Encryption.

The work is based on https://github.com/alexmullins/zip

Available encryption:

zip.StandardEncryption
zip.AES128Encryption
zip.AES192Encryption
zip.AES256Encryption

Warning

Zip Standard Encryption isn't actually secure. Unless you have to work with it, please use AES encryption instead.

Example Encrypt Zip

package main

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

	"github.com/linbaozhong/zip"
)

func main() {
	contents := []byte("Hello World")
	fzip, err := os.Create(`./test.zip`)
	if err != nil {
		log.Fatalln(err)
	}
	zipw := zip.NewWriter(fzip)
	defer zipw.Close()
	w, err := zipw.Encrypt(`test.txt`, `golang`, zip.AES256Encryption)
	if err != nil {
		log.Fatal(err)
	}
	_, err = io.Copy(w, bytes.NewReader(contents))
	if err != nil {
		log.Fatal(err)
	}
	zipw.Flush()
}

Example Decrypt Zip

package main

import (
	"fmt"
	"io/ioutil"
	"log"

	"github.com/linbaozhong/zip"
)

func main() {
	r, err := zip.OpenReader("encrypted.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	for _, f := range r.File {
		if f.IsEncrypted() {
			f.SetPassword("12345")
		}

		r, err := f.Open()
		if err != nil {
			log.Fatal(err)
		}

		buf, err := ioutil.ReadAll(r)
		if err != nil {
			log.Fatal(err)
		}
		defer r.Close()

		fmt.Printf("Size of %v: %v byte(s)\n", f.Name, len(buf))
	}
}

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  //压缩
	WinZipAes uint16 = 99 //压缩并AES加密
)

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")
)

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 (
	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) OpenRaw added in v0.0.12

func (f *File) OpenRaw() (io.Reader, error)

OpenRaw returns a Reader that provides access to the File's contents without decompression.

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
	ModifiedTime       uint16 // MS-DOS time
	ModifiedDate       uint16 // MS-DOS date
	CRC32              uint32
	CompressedSize     uint32 // Use CompressedSize64 instead.
	UncompressedSize   uint32 // Use UncompressedSize64 instead.
	CompressedSize64   uint64
	UncompressedSize64 uint64
	Extra              []byte
	ExternalAttrs      uint32 // Meaning depends on CreatorVersion
	Comment            string

	// 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
	HiddenComment []byte // 新增隐藏注释字段
	// contains filtered or unexported fields
}
Example
package main

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

	"github.com/linbaozhong/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.

type Writer

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

Writer 实现了一个zip文件写入器。

Example
package main

import (
	"bytes"
	"log"

	"github.com/linbaozhong/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 返回一个新的Writer,用于向w写入zip文件。

func (*Writer) Close

func (w *Writer) Close() error

Close 通过写入中央目录完成zip文件的写入。 它不会(也不能)关闭底层写入器。

func (*Writer) Copy added in v0.0.12

func (w *Writer) Copy(f *File) error

Copy copies the file f (obtained from a Reader) into w. It copies the raw form directly bypassing decompression, compression, and validation.

func (*Writer) Create

func (w *Writer) Create(name string) (io.Writer, error)

Create 使用提供的名称向zip文件添加一个文件。 它返回一个Writer,文件内容应写入其中。 名称必须是相对路径:不能以驱动器字母(例如C:)或前导斜杠开头, 并且只允许使用正斜杠。 在下一次调用Create、CreateHeader或Close之前,必须将文件内容写入io.Writer。

func (*Writer) CreateHeader

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

CreateHeader 使用提供的FileHeader为文件元数据向zip文件添加一个文件。 它返回一个Writer,文件内容应写入其中。

在下一次调用Create、CreateHeader或Close之前,必须将文件内容写入io.Writer。 提供的FileHeader fh在调用CreateHeader后不得修改。

func (*Writer) CreateRaw added in v0.0.12

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

CreateRaw adds a file to the zip archive using the provided FileHeader and 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 Writer.Create, Writer.CreateHeader, Writer.CreateRaw, or Writer.Close.

In contrast to Writer.CreateHeader, the bytes passed to Writer are not compressed.

CreateRaw's argument is stored in w. If the argument is a pointer to the embedded FileHeader in a File obtained from a Reader created from in-memory data, then w will refer to all of that memory.

func (*Writer) Encrypt

func (w *Writer) Encrypt(name string, password string, enc EncryptionMethod) (io.Writer, error)

Encrypt adds a file to the zip file using the provided name. It returns a Writer to which the file contents should be written. File contents will be encrypted with AES-256 using the given password. The file's contents must be written to the io.Writer before the next call to Create, CreateHeader, or Close.

Example
package main

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

	"github.com/linbaozhong/zip"
)

func main() {
	contents := []byte("Hello World")

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

	// 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()
	}
}
Output:

Hello World

func (*Writer) Flush

func (w *Writer) Flush() error

Flush 将任何缓冲数据刷新到底层写入器。 通常不需要调用Flush;调用Close就足够了。

func (*Writer) IsClosed added in v0.0.6

func (w *Writer) IsClosed() bool

func (*Writer) SetGlobalComment

func (w *Writer) SetGlobalComment(comment string)

SetGlobalComment 设置全局注释

func (*Writer) SetHiddenComment

func (w *Writer) SetHiddenComment(comment []byte)

SetHiddenComment 设置隐藏注释

func (*Writer) SetOffset

func (w *Writer) SetOffset(n int64)

SetOffset 设置zip数据在底层写入器中的起始偏移量。 当zip数据附加到现有文件(如二进制可执行文件)时应使用此方法。 必须在写入任何数据之前调用。

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