Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 0 additions & 26 deletions .gitignore

This file was deleted.

44 changes: 27 additions & 17 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
The MIT License (MIT)
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright (c) 2015 Alex Mullins
Copyright (c) 2016 Yakub Kristianto
Copyright (c) 2019 Hilko Bengen

Copyright (C) 2015 Alex Mullins
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
100 changes: 11 additions & 89 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,92 +1,14 @@
This fork add support for Standard Zip Encryption.
# Go `archive/zip` plus encryption support

The work is based on https://github.com/alexmullins/zip
[![GoDoc](https://godoc.org/github.com/hillu/go-archive-zip-crypto?status.svg)](https://godoc.org/github.com/hillu/go-archive-zip-crypto)
[![Go Report Card](https://goreportcard.com/badge/github.com/hillu/go-archive-zip-crypto)](https://goreportcard.com/report/github.com/hillu/go-archive-zip-crypto)

Available encryption:
This is a fork of the `archive/zip` package from the Go standard
library which adds support for both the legacy
(insecure) ZIP encryption scheme and for newer AES-based encryption
schemes introduced with WinZip. It is based on Go 1.14.

```
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/yeka/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/yeka/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))
}
}
```
This is based on work by [Alex Mullins](https://github.com/alexmullins/zip) and
[Yakub Kristianto](https://github.com/yeka/zip). The forward-port was done to
introduce bugfixes and enhancements, such as missing support for large
(>= 4GB) ZIP files like those distributed by [VirusShare](https://virusshare.com/).
9 changes: 5 additions & 4 deletions crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ func encryptStream(key []byte, w io.Writer) (io.Writer, error) {
// data. The authcode will be written out in fileWriter.close().
func newEncryptionWriter(w io.Writer, password passwordFn, fw *fileWriter, aesstrength byte) (io.Writer, error) {
keysize := aesKeyLen(aesstrength)
salt := make([]byte, keysize / 2)
salt := make([]byte, keysize/2)
_, err := rand.Read(salt[:])
if err != nil {
return nil, errors.New("zip: unable to generate random salt")
Expand Down Expand Up @@ -428,7 +428,7 @@ func (h *FileHeader) writeWinZipExtra() {
// total size is 11 bytes
var buf [11]byte
eb := writeBuf(buf[:])
eb.uint16(winzipAesExtraId) // 0x9901
eb.uint16(winzipAesExtraID) // 0x9901
eb.uint16(7) // following data size is 7
eb.uint16(2) // ae 2
eb.uint16(0x4541) // "AE"
Expand All @@ -437,7 +437,8 @@ func (h *FileHeader) writeWinZipExtra() {
h.Extra = append(h.Extra, buf[:]...)
}

func (h *FileHeader) setEncryptionMethod(enc EncryptionMethod) {
// SetEncryptionMethod sets the method used for encryption.
func (h *FileHeader) SetEncryptionMethod(enc EncryptionMethod) {
h.encryption = enc
switch enc {
case AES128Encryption:
Expand Down Expand Up @@ -478,6 +479,6 @@ func (w *Writer) Encrypt(name string, password string, enc EncryptionMethod) (io
Method: Deflate,
}
fh.SetPassword(password)
fh.setEncryptionMethod(enc)
fh.SetEncryptionMethod(enc)
return w.CreateHeader(fh)
}
49 changes: 42 additions & 7 deletions crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func TestPasswordReadSimple(t *testing.T) {
var buf bytes.Buffer
r, err := OpenReader(filepath.Join("testdata", file))
if err != nil {
t.Errorf("Expected %s to open: %v.", file, err)
t.Fatalf("Expected %s to open: %v.", file, err)
}
defer r.Close()
if len(r.File) != 1 {
Expand All @@ -29,7 +29,7 @@ func TestPasswordReadSimple(t *testing.T) {
f.SetPassword("golang")
rc, err := f.Open()
if err != nil {
t.Errorf("Expected to open the readcloser: %v.", err)
t.Fatalf("Expected to open the readcloser: %v.", err)
}
_, err = io.Copy(&buf, rc)
if err != nil {
Expand All @@ -56,12 +56,12 @@ func TestPasswordHelloWorldAes(t *testing.T) {
var b bytes.Buffer
for _, f := range r.File {
if !f.IsEncrypted() {
t.Errorf("Expected %s to be encrypted.", f.FileInfo().Name)
t.Errorf("Expected %s to be encrypted.", f.FileInfo().Name())
}
f.SetPassword("golang")
rc, err := f.Open()
if err != nil {
t.Errorf("Expected to open readcloser: %v", err)
t.Fatalf("Expected to open readcloser: %v", err)
}
defer rc.Close()
if _, err := io.Copy(&b, rc); err != nil {
Expand Down Expand Up @@ -91,7 +91,7 @@ func TestPasswordMacbethAct1(t *testing.T) {
f.SetPassword("golang")
rc, err := f.Open()
if err != nil {
t.Errorf("Expected to open readcloser: %v", err)
t.Fatalf("Expected to open readcloser: %v", err)
}
defer rc.Close()
if _, err := io.Copy(&b, rc); err != nil {
Expand Down Expand Up @@ -131,7 +131,7 @@ func TestPasswordAE1BadCRC(t *testing.T) {
f.SetPassword("golang")
rc, err := f.Open()
if err != nil {
t.Errorf("Expected the readcloser to open.")
t.Fatalf("Expected the readcloser to open.")
}
defer rc.Close()
if _, err := io.Copy(buf, rc); err != ErrChecksum {
Expand Down Expand Up @@ -162,7 +162,7 @@ func TestPasswordTamperedData(t *testing.T) {
f.SetPassword("golang")
rc, err := f.Open()
if err != nil {
t.Errorf("Expected the readcloser to open.")
t.Fatalf("Expected the readcloser to open.")
}
defer rc.Close()
if _, err := io.Copy(buf, rc); err != ErrAuthentication {
Expand Down Expand Up @@ -244,3 +244,38 @@ func TestZipCrypto(t *testing.T) {
t.Errorf("Expected the unzipped contents to equal '%s', but was '%s' instead", contents, res.Bytes())
}
}

func TestZipCryptoSetMethod(t *testing.T) {
contents := []byte("Hello World")
conLen := len(contents)

raw := new(bytes.Buffer)
zipw := NewWriter(raw)

fh := &FileHeader{
Name: "hello.txt",
Method: Deflate,
}
fh.SetPassword("golang")
fh.SetEncryptionMethod(StandardEncryption)
w, err := zipw.CreateHeader(fh)
if err != nil {
t.Errorf("Expected to create a new FileHeader")
}
n, err := io.Copy(w, bytes.NewReader(contents))
if err != nil || n != int64(conLen) {
t.Errorf("Expected to write the full contents to the writer.")
}
zipw.Close()

zipr, _ := NewReader(bytes.NewReader(raw.Bytes()), int64(raw.Len()))
zipr.File[0].SetPassword("golang")
r, _ := zipr.File[0].Open()
res := new(bytes.Buffer)
io.Copy(res, r)
r.Close()

if !bytes.Equal(contents, res.Bytes()) {
t.Errorf("Expected the unzipped contents to equal '%s', but was '%s' instead", contents, res.Bytes())
}
}
20 changes: 19 additions & 1 deletion example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ package zip_test

import (
"bytes"
"compress/flate"
"fmt"
"io"
"log"
"os"

"github.com/yeka/zip"
"github.com/kdungs/zip"
)

func ExampleWriter() {
Expand Down Expand Up @@ -75,6 +76,23 @@ func ExampleReader() {
// This is the source code repository for the Go programming language.
}

func ExampleWriter_RegisterCompressor() {
// Override the default Deflate compressor with a higher compression level.

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

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

// Register a custom Deflate compressor.
w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
return flate.NewWriter(out, flate.BestCompression)
})

// Proceed to add files to w.
}

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

Expand Down
Loading