Unzipping Password-Protected ZIP Files in Go 1.2
The archive/zip package in Go 1.2 provides basic functionality for handling ZIP archives but lacks support for password protection. To unzip a ZIP file protected by a password, one can utilize the os/exec package to invoke an external tool such as 7zip.
To do so, follow these steps:
7za a sample.zip name.txt -p"your_password" -mem=AES256
<code class="go">import ( "fmt" "os/exec" ) func extractZipWithPassword() { fmt.Printf("Unzipping `%s` to directory `%s`\n", zip_path, extract_path) commandString := fmt.Sprintf(`7za e %s -o%s -p"%s" -aoa`, zip_path, extract_path, zip_password) commandSlice := strings.Fields(commandString) fmt.Println(commandString) c := exec.Command(commandSlice[0], commandSlice[1:]...) e := c.Run() checkError(e) }</code>
In this code snippet:
<code class="go">// Shows how to extract an passsword encrypted zip file using 7zip. // By Larry Battle <https://github.com/LarryBattle> // Answer to http://stackoverflow.com/questions/20330210/golang-1-2-unzip-password-protected-zip-file // 7-zip.chm - http://sevenzip.sourceforge.jp/chm/cmdline/switches/index.htm // Effective Golang - http://golang.org/doc/effective_go.html package main import ( "fmt" "os" "os/exec" "path/filepath" "strings" ) // ... func main() { // ... extractZipWithPassword() // ... }</code>
go run main.go
The program will extract the password-protected ZIP file to the specified directory.
The above is the detailed content of How to Unzip Password-Protected ZIP Files in Go 1.2?. For more information, please follow other related articles on the PHP Chinese website!