暴力破解PDF密码#
package main
// main.go
//
// A multi-goroutine brute-forcer for the *user password* of a locally-stored,
// encrypted PDF that uses the Standard Security Handler (V1..V4 / R2..R4,
// RC4 or AES-128). It tries every password of length MinPasswordLength up to
// MaxPasswordLength over a configurable character set, and stops as soon as a
// match is found.
//
// Only for PDFs you own / are authorized to test.
import (
"fmt"
"math/big"
"os"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
)
// ===========================================================================
// 配置区:所有参数都是常量。修改后重新编译运行即可(go build -o pdfcrack.exe .)。
// Configuration: every parameter is a constant. Edit, then rebuild and run.
// ===========================================================================
const (
// PDFPath 要破解的 PDF 文件路径。
// PDFPath is the path to the encrypted PDF to attack.
PDFPath = "1.pdf"
// MinPasswordLength / MaxPasswordLength 密码长度范围。
// 程序从 MinPasswordLength 位开始,逐位增加,一直尝试到 MaxPasswordLength 位,
// 而不是只尝试固定长度。默认 1..10。
// The search runs incrementally: length 1, then 2, ... up to
// MaxPasswordLength. It does NOT test only the maximum length.
MinPasswordLength = 1
MaxPasswordLength = 10
// 字符集开关:决定尝试哪些字符。true=启用。
// Character-set toggles (true = include).
UseDigits = true // 数字 0-9
UseLower = true // 小写字母 a-z
UseUpper = true // 大写字母 A-Z
UseSpecial = true // 常用特殊字符(见 SpecialChars)
// SpecialChars 常用特殊字符集合(当 UseSpecial=true 时使用)。
// 注意:这是 Go 字符串字面量,反斜杠和双引号需转义(\\ 和 \")。
// The set of "common special characters" used when UseSpecial is true.
SpecialChars = "!@#$%^&*()-_=+[]{};:,.?/|~"
// Workers 并发协程数量。0 表示自动使用 CPU 核心数。
// Number of concurrent goroutines. 0 = use runtime.NumCPU().
Workers = 0
// InfoOnly 为 true 时只打印加密参数然后退出(不进行破解),用于确认解析是否正确。
// When true, only print the parsed encryption parameters and exit.
InfoOnly = false
)
// Derived character-set pieces.
const (
digitsSet = "0123456789"
lowerSet = "abcdefghijklmnopqrstuvwxyz"
upperSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func main() {
minLen := MinPasswordLength
maxLen := MaxPasswordLength
workers := Workers
if workers <= 0 {
workers = runtime.NumCPU()
}
data, err := os.ReadFile(PDFPath)
if err != nil {
fatalf("cannot read PDF %q: %v", PDFPath, err)
}
enc, err := ParseEncryption(data)
if err != nil {
fatalf("parse encryption: %v", err)
}
fmt.Printf("PDF: %s\n", PDFPath)
fmt.Printf("Encryption: %s\n", enc.Summary())
fmt.Printf("Encrypt obj: %d 0 R /O=%s /U=%s\n",
enc.EncryptObj, shortHex(enc.O), shortHex(enc.U))
if !enc.Supported() {
fatalf("revision R%d is not supported (only R2..R4 / RC4 & AES-128). "+
"R5/R6 use an AES-256 SHA-based scheme not implemented here.", enc.R)
}
if InfoOnly {
return
}
charset := buildCharset(UseDigits, UseLower, UseUpper, UseSpecial, SpecialChars)
if len(charset) == 0 {
fatalf("empty character set: enable at least one of UseDigits/UseLower/UseUpper/UseSpecial")
}
if minLen < 1 {
minLen = 1
}
if maxLen > 32 {
fmt.Println("note: capping max length at 32 (PDF passwords are padded/truncated to 32 bytes)")
maxLen = 32
}
fmt.Printf("Charset: %d chars: %s\n", len(charset), previewCharset(charset))
fmt.Printf("Lengths: %d..%d Workers: %d\n", minLen, maxLen, workers)
fmt.Printf("Total search space: %s combinations\n\n", totalCombos(len(charset), minLen, maxLen))
cr := newCracker(enc, charset, workers)
// Free courtesy check: many PDFs are encrypted with an *empty* user
// password (only the owner password restricts permissions). Test it first.
if enc.NewVerifier().Check(nil) {
fmt.Println("==> The user password is EMPTY (document opens without a password).")
fmt.Println(" (It still has an owner password / permission restrictions.)")
return
}
start := time.Now()
stop := make(chan struct{})
go cr.report(stop, start)
for L := minLen; L <= maxLen; L++ {
if pw, ok := cr.crackLength(L); ok {
close(stop)
elapsed := time.Since(start)
fmt.Printf("\n\n*** PASSWORD FOUND: %q ***\n", pw)
fmt.Printf("length=%d tried=%d elapsed=%s\n",
len(pw), atomic.LoadUint64(&cr.total), elapsed.Round(time.Millisecond))
return
}
}
close(stop)
fmt.Printf("\n\nExhausted lengths %d..%d over %d-char set. No password found (tried %d combinations in %s).\n",
minLen, maxLen, len(charset), atomic.LoadUint64(&cr.total), time.Since(start).Round(time.Second))
}
// ---------------------------------------------------------------------------
// Brute-force engine
// ---------------------------------------------------------------------------
type cracker struct {
enc *EncInfo
charset []byte
workers int
total uint64 // total attempts (approx, batched)
progress []uint64 // per-worker attempt counters
curLen int32 // length currently being searched (for reporting)
}
func newCracker(enc *EncInfo, charset []byte, workers int) *cracker {
return &cracker{
enc: enc,
charset: charset,
workers: workers,
progress: make([]uint64, workers),
}
}
// crackLength tries every password of exactly length L. Work is partitioned by
// the first character: each of the base "first-char" values is a task, handed
// out to workers via an atomic counter. Each task enumerates the remaining L-1
// positions with an odometer. This both parallelizes the search and keeps the
// per-task index space within uint64 (base^(L-1)).
func (c *cracker) crackLength(L int) (string, bool) {
atomic.StoreInt32(&c.curLen, int32(L))
base := len(c.charset)
var (
nextTask int64 = -1
found int32
result string
resMu sync.Mutex
wg sync.WaitGroup
)
for id := range c.workers {
wg.Add(1)
go func(id int) {
defer wg.Done()
v := c.enc.NewVerifier()
pw := make([]byte, L)
idx := make([]int, L)
var local uint64
flush := func() {
if local > 0 {
atomic.AddUint64(&c.progress[id], local)
atomic.AddUint64(&c.total, local)
local = 0
}
}
for {
if atomic.LoadInt32(&found) != 0 {
flush()
return
}
t := int(atomic.AddInt64(&nextTask, 1))
if t >= base {
flush()
return
}
// Initialize the odometer for this task.
pw[0] = c.charset[t]
for p := 1; p < L; p++ {
idx[p] = 0
pw[p] = c.charset[0]
}
for {
if v.Check(pw) {
resMu.Lock()
result = string(pw)
resMu.Unlock()
atomic.StoreInt32(&found, 1)
flush()
return
}
local++
if local >= 4096 {
flush()
if atomic.LoadInt32(&found) != 0 {
return
}
}
// Increment odometer positions L-1 .. 1.
p := L - 1
for ; p >= 1; p-- {
idx[p]++
if idx[p] < base {
pw[p] = c.charset[idx[p]]
break
}
idx[p] = 0
pw[p] = c.charset[0]
}
if p < 1 {
break // finished this first-character task
}
}
}
}(id)
}
wg.Wait()
if atomic.LoadInt32(&found) != 0 {
return result, true
}
return "", false
}
// report prints a periodic progress line until stop is closed.
func (c *cracker) report(stop <-chan struct{}, start time.Time) {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
var last uint64
lastT := start
for {
select {
case <-stop:
return
case now := <-ticker.C:
total := atomic.LoadUint64(&c.total)
dt := now.Sub(lastT).Seconds()
rate := float64(total-last) / dt
last, lastT = total, now
fmt.Printf("\r[len %d] tried %-14d %8.0f/s elapsed %s ",
atomic.LoadInt32(&c.curLen), total, rate,
time.Since(start).Round(time.Second))
}
}
}
// ---------------------------------------------------------------------------
// Charset + helpers
// ---------------------------------------------------------------------------
func buildCharset(digits, lower, upper, special bool, specialChars string) []byte {
var sb strings.Builder
if digits {
sb.WriteString(digitsSet)
}
if lower {
sb.WriteString(lowerSet)
}
if upper {
sb.WriteString(upperSet)
}
if special {
sb.WriteString(specialChars)
}
// De-duplicate while preserving order.
seen := make(map[byte]bool, sb.Len())
out := make([]byte, 0, sb.Len())
for _, ch := range []byte(sb.String()) {
if !seen[ch] {
seen[ch] = true
out = append(out, ch)
}
}
return out
}
func previewCharset(cs []byte) string {
s := string(cs)
if len(s) > 60 {
return s[:60] + "..."
}
return s
}
// totalCombos returns base^min + ... + base^max as a decimal string.
func totalCombos(base, min, max int) string {
sum := big.NewInt(0)
b := big.NewInt(int64(base))
term := new(big.Int).Exp(b, big.NewInt(int64(min)), nil)
for L := min; L <= max; L++ {
sum.Add(sum, term)
term.Mul(term, b)
}
return sum.String()
}
func shortHex(b []byte) string {
const n = 8
if len(b) > n {
return fmt.Sprintf("%x...", b[:n])
}
return fmt.Sprintf("%x", b)
}
func fatalf(format string, args ...any) {
fmt.Fprintf(os.Stderr, "error: "+format+"\n", args...)
os.Exit(1)
}
package main
// pdfsec.go
//
// Implements the PDF "Standard Security Handler" password authentication as
// defined in ISO 32000-1:2008 (PDF 1.7), sections 7.6.3.3 / 7.6.3.4.
//
// It supports revisions R2, R3 and R4 (V1..V4). For these revisions the
// password check is based on MD5 (key derivation, Algorithm 2) and RC4
// (computing the /U value, Algorithm 4/5) -- regardless of whether the actual
// document streams are encrypted with RC4 or AES-128 (AESV2). That means we can
// verify a candidate user password *without* ever running AES.
//
// R5/R6 (AES-256, PDF 2.0 / ISO 32000-2) use a completely different SHA-based
// scheme and are reported as unsupported.
import (
"bytes"
"crypto/md5"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
)
// pad is the 32-byte password padding string from the PDF spec (Algorithm 2).
var pad = []byte{
0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
}
// EncInfo holds the parsed encryption parameters plus values precomputed once
// so that testing a password is as cheap as possible.
type EncInfo struct {
// Raw parsed fields.
V, R, Length int // version, revision, key length in bits
P int32 // permissions
O, U []byte // 32-byte owner/user hashes
ID []byte // first element of trailer /ID
EncMetadata bool // whether metadata is encrypted (default true)
CFM string // crypt-filter method for the standard filter (e.g. AESV2)
EncryptObj int // object number of the /Encrypt dictionary
// Precomputed helpers.
keyLen int // Length/8
keyTail []byte // O || P(le) || ID [|| 0xFFFFFFFF] (constant suffix for Alg.2)
hConst [16]byte
}
// Supported reports whether we can brute-force this handler.
func (e *EncInfo) Supported() bool {
return e.R >= 2 && e.R <= 4
}
func (e *EncInfo) Summary() string {
return fmt.Sprintf(
"Filter=Standard V=%d R=%d KeyLength=%d bits CFM=%s EncryptMetadata=%v P=%d",
e.V, e.R, e.Length, cfmOrRC4(e.CFM), e.EncMetadata, e.P)
}
func cfmOrRC4(cfm string) string {
if cfm == "" {
return "V2 (RC4)"
}
return cfm
}
// prepare fills in keyLen, keyTail and hConst from the raw fields.
func (e *EncInfo) prepare() {
e.keyLen = e.Length / 8
if e.keyLen == 0 {
e.keyLen = 5 // 40-bit default (V1)
}
var pbuf [4]byte
binary.LittleEndian.PutUint32(pbuf[:], uint32(e.P))
tail := make([]byte, 0, len(e.O)+4+len(e.ID)+4)
tail = append(tail, e.O...)
tail = append(tail, pbuf[:]...)
tail = append(tail, e.ID...)
if e.R >= 4 && !e.EncMetadata {
tail = append(tail, 0xFF, 0xFF, 0xFF, 0xFF)
}
e.keyTail = tail
// hConst = MD5(pad || ID) -- constant across all candidate passwords
// (Algorithm 5, step (b) for R>=3 / Algorithm 4 for R2).
h := md5.New()
h.Write(pad)
h.Write(e.ID)
copy(e.hConst[:], h.Sum(nil))
}
// Verifier tests candidate user passwords for a single goroutine. It carries
// per-worker scratch buffers so that a check performs zero heap allocations.
type Verifier struct {
e *EncInfo
h hash.Hash // reused MD5 hasher
pad32 [32]byte
sum [16]byte
key [16]byte
tmpKey [16]byte
bufA [16]byte
bufB [16]byte
rc4s [256]byte
}
func (e *EncInfo) NewVerifier() *Verifier {
return &Verifier{e: e, h: md5.New()}
}
// Check reports whether pw is the correct user password. pw must be <= 32 bytes
// (which the brute-forcer guarantees since max length is capped at 32).
func (v *Verifier) Check(pw []byte) bool {
e := v.e
kl := e.keyLen
// --- Algorithm 2: compute the encryption key from the padded password. ---
n := copy(v.pad32[:], pw)
if n < 32 {
copy(v.pad32[n:], pad[:32-n])
}
v.h.Reset()
v.h.Write(v.pad32[:])
v.h.Write(e.keyTail)
copy(v.sum[:], v.h.Sum(v.bufA[:0]))
if e.R >= 3 {
for range 50 {
v.sum = md5.Sum(v.sum[:kl])
}
}
copy(v.key[:kl], v.sum[:kl])
// --- Algorithm 4 (R2) / Algorithm 5 (R>=3): compute the /U value. ---
if e.R == 2 {
// U = RC4(key, pad); compare all 32 bytes.
var out [32]byte
rc4Crypt(v.key[:kl], pad, out[:], &v.rc4s)
return bytes.Equal(out[:], e.U[:32])
}
// R>=3: RC4 hConst with key, then 19 more rounds with key XOR i.
cur := v.bufA[:16]
nxt := v.bufB[:16]
rc4Crypt(v.key[:kl], e.hConst[:], cur, &v.rc4s)
for i := 1; i <= 19; i++ {
for j := range kl {
v.tmpKey[j] = v.key[j] ^ byte(i)
}
rc4Crypt(v.tmpKey[:kl], cur, nxt, &v.rc4s)
cur, nxt = nxt, cur
}
// Only the first 16 bytes of /U are significant for R>=3.
return bytes.Equal(cur[:16], e.U[:16])
}
// rc4Crypt encrypts src into dst (len(dst) must be >= len(src)) using RC4 with
// the given key. It uses the caller-provided state array to avoid allocation.
func rc4Crypt(key, src, dst []byte, s *[256]byte) {
for i := range 256 {
s[i] = byte(i)
}
j := 0
kl := len(key)
for i := range 256 {
j = (j + int(s[i]) + int(key[i%kl])) & 0xff
s[i], s[j] = s[j], s[i]
}
a, b := 0, 0
for k := range src {
a = (a + 1) & 0xff
b = (b + int(s[a])) & 0xff
s[a], s[b] = s[b], s[a]
dst[k] = src[k] ^ s[(int(s[a])+int(s[b]))&0xff]
}
}
// ---------------------------------------------------------------------------
// Minimal PDF parsing: just enough to find the /Encrypt dictionary and the
// trailer /ID, and to read the fields we need out of the encryption dict.
// ---------------------------------------------------------------------------
// ParseEncryption locates and parses the standard encryption dictionary.
func ParseEncryption(data []byte) (*EncInfo, error) {
trailer := trailerRegion(data)
objNum, ok := findEncryptRef(trailer)
if !ok {
if objNum, ok = findEncryptRef(data); !ok {
return nil, fmt.Errorf("no /Encrypt reference found; the PDF may not be encrypted")
}
}
id, ok := findFileID(trailer)
if !ok {
if id, ok = findFileID(data); !ok {
return nil, fmt.Errorf("no trailer /ID array found")
}
}
dict, ok := findObject(data, objNum)
if !ok {
return nil, fmt.Errorf("could not locate encryption object %d 0 obj", objNum)
}
e := &EncInfo{
EncMetadata: true, // default per spec
ID: id,
EncryptObj: objNum,
}
// Parse only the top-level keys of the encryption dictionary. This is what
// makes /Length resolve to the document key length (128) and not the crypt
// filter's byte length (16), and it never matches bytes that merely *look*
// like keys inside the binary /O and /U strings.
top := parseDict(dict)
if p, ok := top["Filter"]; ok {
if name := readName(dict, p); name != "Standard" {
return nil, fmt.Errorf("unsupported security handler /Filter /%s (only Standard is supported)", name)
}
}
var perr error
e.V = topInt(dict, top, "V", 0, true, &perr)
e.R = topInt(dict, top, "R", 0, true, &perr)
e.Length = topInt(dict, top, "Length", 40, false, &perr)
e.P = int32(topInt(dict, top, "P", 0, false, &perr))
if perr != nil {
return nil, perr
}
o, ok := readStringAt(dict, top, "O")
if !ok {
return nil, fmt.Errorf("could not read /O")
}
u, ok := readStringAt(dict, top, "U")
if !ok {
return nil, fmt.Errorf("could not read /U")
}
e.O = padOrTrim(o, 32)
e.U = padOrTrim(u, 32)
if p, ok := top["EncryptMetadata"]; ok {
e.EncMetadata = readBool(dict, p)
}
e.CFM = findCFM(dict, top)
if e.R < 2 {
return nil, fmt.Errorf("invalid or missing /R revision (%d)", e.R)
}
e.prepare()
return e, nil
}
// padOrTrim returns b resized to exactly n bytes (zero-padded or truncated).
func padOrTrim(b []byte, n int) []byte {
out := make([]byte, n)
copy(out, b)
return out
}
// topInt reads an integer for a top-level key. If required and absent, it sets
// *perr; otherwise it returns def.
func topInt(dict []byte, top map[string]int, name string, def int, required bool, perr *error) int {
p, ok := top[name]
if !ok {
if required && *perr == nil {
*perr = fmt.Errorf("missing required /%s in encryption dict", name)
}
return def
}
v, _, ok := scanInt(dict, p)
if !ok {
if *perr == nil {
*perr = fmt.Errorf("could not parse integer for /%s", name)
}
return def
}
return v
}
// readStringAt reads a literal/hex string value for a top-level key.
func readStringAt(dict []byte, top map[string]int, name string) ([]byte, bool) {
p, ok := top[name]
if !ok {
return nil, false
}
b, _, ok := scanStringToken(dict, p)
return b, ok
}
// findCFM digs into /CF /StdCF /CFM to report the crypt-filter method (nested).
func findCFM(dict []byte, top map[string]int) string {
cf, ok := top["CF"]
if !ok || cf >= len(dict) || dict[cf] != '<' {
return ""
}
cfDict := dict[cf:]
cfMap := parseDict(cfDict)
// Use the first standard crypt filter we can find (StdCF is conventional).
for _, name := range []string{"StdCF", "Identity"} {
if sp, ok := cfMap[name]; ok && sp < len(cfDict) && cfDict[sp] == '<' {
stdDict := cfDict[sp:]
if cp, ok := parseDict(stdDict)["CFM"]; ok {
return readName(stdDict, cp)
}
}
}
return ""
}
// trailerRegion returns the bytes from the last "trailer" keyword to EOF, or the
// whole file if there is no classic trailer (e.g. cross-reference streams).
func trailerRegion(data []byte) []byte {
key := []byte("trailer")
last := -1
from := 0
for {
i := indexFrom(data, key, from)
if i < 0 {
break
}
last = i
from = i + len(key)
}
if last < 0 {
return data
}
return data[last:]
}
// findEncryptRef finds "/Encrypt <num> <gen> R" and returns <num>.
func findEncryptRef(data []byte) (int, bool) {
key := []byte("/Encrypt")
best := -1
from := 0
for {
i := indexFrom(data, key, from)
if i < 0 {
break
}
p := skipWS(data, i+len(key))
if num, p2, ok := scanInt(data, p); ok {
p2 = skipWS(data, p2)
if _, p3, ok2 := scanInt(data, p2); ok2 {
p3 = skipWS(data, p3)
if p3 < len(data) && data[p3] == 'R' {
best = num
}
}
}
from = i + len(key)
}
return best, best >= 0
}
// findFileID finds "/ID [ <...> <...> ]" and returns the first element.
func findFileID(data []byte) ([]byte, bool) {
key := []byte("/ID")
var best []byte
found := false
from := 0
for {
i := indexFrom(data, key, from)
if i < 0 {
break
}
p := skipWS(data, i+len(key))
if p < len(data) && data[p] == '[' {
p = skipWS(data, p+1)
if b, _, ok := scanStringToken(data, p); ok {
best = b
found = true
}
}
from = i + len(key)
}
return best, found
}
// findObject returns the dictionary bytes of "<num> 0 obj ... endobj".
func findObject(data []byte, num int) ([]byte, bool) {
// Generation is essentially always 0 for the Encrypt object.
needle := fmt.Appendf(nil, "%d 0 obj", num)
i := indexFrom(data, needle, 0)
if i < 0 {
return nil, false
}
start := i + len(needle)
end := indexFrom(data, []byte("endobj"), start)
if end < 0 {
end = len(data)
}
return data[start:end], true
}
// parseDict parses the first "<< ... >>" dictionary in d and returns a map from
// each top-level key name to the byte offset (in d) where its value begins. It
// walks the dictionary as alternating key/value pairs, skipping over nested
// dictionaries, arrays and strings so that keys inside nested structures (or
// bytes inside binary strings) are never mistaken for top-level keys.
func parseDict(d []byte) map[string]int {
m := make(map[string]int)
s := indexFrom(d, []byte("<<"), 0)
if s < 0 {
return m
}
i := s + 2
for i < len(d) {
i = skipWS(d, i)
if i+1 < len(d) && d[i] == '>' && d[i+1] == '>' {
break
}
if i >= len(d) {
break
}
if d[i] != '/' {
// Out of sync; skip a value and try to recover.
i = skipValue(d, i)
continue
}
q := i + 1
for q < len(d) && isRegular(d[q]) {
q++
}
key := string(d[i+1 : q])
vp := skipWS(d, q)
m[key] = vp
i = skipValue(d, vp)
}
return m
}
// skipValue returns the index just past the PDF object starting at p.
func skipValue(d []byte, p int) int {
if p >= len(d) {
return p
}
switch c := d[p]; {
case c == '(':
_, np, _ := scanLiteralString(d, p)
return np
case c == '<' && p+1 < len(d) && d[p+1] == '<':
return skipDict(d, p)
case c == '<':
_, np, _ := scanHexString(d, p)
return np
case c == '[':
return skipArray(d, p)
case c == '/':
q := p + 1
for q < len(d) && isRegular(d[q]) {
q++
}
return q
case c == '-' || c == '+' || (c >= '0' && c <= '9'):
_, np, _ := scanInt(d, p)
// Possible indirect reference "<int> <int> R".
q := skipWS(d, np)
if _, q2, ok := scanInt(d, q); ok {
q3 := skipWS(d, q2)
if q3 < len(d) && d[q3] == 'R' {
return q3 + 1
}
}
return np
default:
// true / false / null / other bare token.
q := p
for q < len(d) && isRegular(d[q]) {
q++
}
if q == p {
q = p + 1
}
return q
}
}
// skipDict skips a balanced "<< ... >>" beginning at p.
func skipDict(d []byte, p int) int {
i := p + 2
depth := 1
for i < len(d) {
switch {
case d[i] == '<' && i+1 < len(d) && d[i+1] == '<':
depth++
i += 2
case d[i] == '>' && i+1 < len(d) && d[i+1] == '>':
depth--
i += 2
if depth == 0 {
return i
}
case d[i] == '(':
_, i, _ = scanLiteralString(d, i)
case d[i] == '<':
_, i, _ = scanHexString(d, i)
default:
i++
}
}
return i
}
// skipArray skips a balanced "[ ... ]" beginning at p.
func skipArray(d []byte, p int) int {
i := p + 1
depth := 1
for i < len(d) {
switch {
case d[i] == '[':
depth++
i++
case d[i] == ']':
depth--
i++
if depth == 0 {
return i
}
case d[i] == '(':
_, i, _ = scanLiteralString(d, i)
case d[i] == '<' && i+1 < len(d) && d[i+1] == '<':
i = skipDict(d, i)
case d[i] == '<':
_, i, _ = scanHexString(d, i)
default:
i++
}
}
return i
}
// readName parses a /Name value at position p and returns the name (no slash).
func readName(dict []byte, p int) string {
if p >= len(dict) || dict[p] != '/' {
return ""
}
q := p + 1
for q < len(dict) && isRegular(dict[q]) {
q++
}
return string(dict[p+1 : q])
}
func readBool(dict []byte, p int) bool {
return bytes.HasPrefix(dict[p:], []byte("true"))
}
// scanStringToken parses a literal "(...)" or hex "<...>" string starting at p.
func scanStringToken(data []byte, p int) ([]byte, int, bool) {
if p >= len(data) {
return nil, p, false
}
switch data[p] {
case '(':
return scanLiteralString(data, p)
case '<':
return scanHexString(data, p)
}
return nil, p, false
}
// scanLiteralString decodes a PDF literal string beginning at the '(' at p.
func scanLiteralString(data []byte, p int) ([]byte, int, bool) {
if data[p] != '(' {
return nil, p, false
}
out := make([]byte, 0, 64)
depth := 0
i := p
for i < len(data) {
c := data[i]
switch c {
case '\\':
i++
if i >= len(data) {
return out, i, true
}
e := data[i]
switch e {
case 'n':
out = append(out, '\n')
case 'r':
out = append(out, '\r')
case 't':
out = append(out, '\t')
case 'b':
out = append(out, '\b')
case 'f':
out = append(out, '\f')
case '(', ')', '\\':
out = append(out, e)
case '\r':
// line continuation: skip an optional following \n
if i+1 < len(data) && data[i+1] == '\n' {
i++
}
case '\n':
// line continuation
default:
if e >= '0' && e <= '7' {
// up to 3 octal digits
val := int(e - '0')
for k := 0; k < 2 && i+1 < len(data) && data[i+1] >= '0' && data[i+1] <= '7'; k++ {
i++
val = val*8 + int(data[i]-'0')
}
out = append(out, byte(val))
} else {
out = append(out, e) // unknown escape: keep the char
}
}
i++
case '(':
if i != p {
depth++
out = append(out, c)
}
i++
case ')':
if depth == 0 {
return out, i + 1, true
}
depth--
out = append(out, c)
i++
default:
if i != p { // skip the opening '('
out = append(out, c)
}
i++
}
}
return out, i, true
}
// scanHexString decodes a PDF hex string beginning at the '<' at p.
func scanHexString(data []byte, p int) ([]byte, int, bool) {
if data[p] != '<' {
return nil, p, false
}
i := p + 1
digits := make([]byte, 0, 96)
for i < len(data) && data[i] != '>' {
c := data[i]
if isHexDigit(c) {
digits = append(digits, c)
}
i++
}
if len(digits)%2 == 1 {
digits = append(digits, '0') // pad final nibble
}
out := make([]byte, len(digits)/2)
if _, err := hex.Decode(out, digits); err != nil {
return nil, i, false
}
return out, i + 1, true
}
// ---- low-level byte helpers ----
func indexFrom(data, sub []byte, from int) int {
if from < 0 {
from = 0
}
if from >= len(data) {
return -1
}
i := bytes.Index(data[from:], sub)
if i < 0 {
return -1
}
return from + i
}
func scanInt(data []byte, p int) (val int, next int, ok bool) {
i := p
neg := false
if i < len(data) && (data[i] == '-' || data[i] == '+') {
neg = data[i] == '-'
i++
}
start := i
for i < len(data) && data[i] >= '0' && data[i] <= '9' {
val = val*10 + int(data[i]-'0')
i++
}
if i == start {
return 0, p, false
}
if neg {
val = -val
}
return val, i, true
}
func skipWS(data []byte, p int) int {
for p < len(data) && isWhitespace(data[p]) {
p++
}
return p
}
func isWhitespace(c byte) bool {
switch c {
case 0x00, 0x09, 0x0A, 0x0C, 0x0D, 0x20:
return true
}
return false
}
func isDelimiter(c byte) bool {
switch c {
case '(', ')', '<', '>', '[', ']', '{', '}', '/', '%':
return true
}
return false
}
// isRegular reports whether c is a PDF "regular" character (part of a name).
func isRegular(c byte) bool {
return !isWhitespace(c) && !isDelimiter(c)
}
func isHexDigit(c byte) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
Excel工作表保护密码爆破器#
package main
// xlsxcrack/main.go
//
// 一个多协程的 Excel“工作表保护”密码爆破器,针对 Excel 2013+ 使用的
// SHA-512 + 盐 + spinCount 迭代哈希(sheetProtection 里的
// algorithmName="SHA-512" hashValue/saltValue/spinCount)。
// 风格与本仓库的 PDF 爆破器(../main.go)一致:所有参数都是常量,
// 改完重新编译运行即可。
//
// A multi-goroutine brute-forcer for Excel *worksheet protection* passwords
// that use the modern SHA-512 scheme (Excel 2013+). It reads the target
// .xlsx directly (it is a zip), lists every protected sheet, then attacks the
// chosen sheet with an optional wordlist followed by an incremental
// charset-based brute force. Stops as soon as a password matches.
//
// 算法已用 excelize 生成的已知样本反向验证:
// H0 = SHA512(salt || UTF16LE(password))
// Hi = SHA512(H(i-1) || LE32(i-1)), i = 0 .. spinCount-1
// hashValue = base64(H(spinCount-1))
//
// 运行 / Run:
// go run ./xlsxcrack
// 或 go build -o xlsxcrack.exe ./xlsxcrack && ./xlsxcrack.exe
//
// 只用于你自己拥有 / 有权测试的文件。
// Only for files you own or are authorized to test.
import (
"archive/zip"
"bufio"
"bytes"
"crypto/sha512"
"encoding/base64"
"encoding/binary"
"fmt"
"math/big"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf16"
)
// ===========================================================================
// 配置区:所有参数都是常量。修改后重新编译运行即可。
// Configuration: every parameter is a constant. Edit, then rebuild and run.
// ===========================================================================
const (
// XlsxPath 要破解的 Excel 文件路径(相对仓库根目录)。
// Path to the .xlsx to attack (relative to the repo root).
XlsxPath = "20231213.xlsx"
// TargetSheet 指定攻击哪一个工作表的 SHA-512 保护。
// "" = 自动选择第一个 SHA-512 保护的工作表
// "sheet4" = 按 zip 内文件名指定(xl/worksheets/sheet4.xml)
// 各工作表若用同一个密码,破出任意一个即可解锁全部。
// Which sheet's SHA-512 protection to attack. "" = auto-pick the first.
// Use the zip filename base, e.g. "sheet4".
TargetSheet = ""
// InfoOnly 为 true 时只列出所有工作表的保护信息然后退出,不破解。
// When true, only list every sheet's protection info and exit.
InfoOnly = false
// -------- 字典攻击 / Wordlist phase(先跑,最实用) --------
// WordlistPath 非空时,先逐行尝试字典里的每个候选(UTF-8,一行一个)。
// spinCount=100000 让纯爆破很慢,字典几乎总是更划算。留空则跳过。
// If non-empty, try each line of this file first (one candidate per line).
WordlistPath = ""
// -------- 暴力枚举 / Brute-force phase --------
// DoBruteForce 为 false 时只跑字典(若配置了)。
DoBruteForce = true
// 密码长度范围:从 MinPasswordLength 位逐位增加到 MaxPasswordLength 位。
// 注意本机实测约 600 候选/秒,长度每+1 时间×字符集大小,务必量力而行。
// Incremental length search. NOTE: ~600 guesses/sec on this machine, so
// keep the space small. See the printed time estimate before committing.
MinPasswordLength = 1
MaxPasswordLength = 5
// 字符集开关 / Character-set toggles (true = include).
UseDigits = true // 0-9
UseLower = true // a-z
UseUpper = true // A-Z
UseSpecial = false // 见 SpecialChars
// SpecialChars 常用特殊字符(Go 字符串字面量,\\ 与 \" 需转义)。
SpecialChars = "!@#$%^&*()-_=+[]{};:,.?/|~"
// Workers 并发协程数量。0 = 使用 CPU 核心数。
// Number of goroutines. 0 = runtime.NumCPU().
Workers = 0
)
// 派生字符集 / Derived charset pieces.
const (
digitsSet = "0123456789"
lowerSet = "abcdefghijklmnopqrstuvwxyz"
upperSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
// ---------------------------------------------------------------------------
// 工作表保护信息 / Parsed sheet-protection info
// ---------------------------------------------------------------------------
type Protection struct {
File string // zip 内文件名,如 "sheet4.xml"
Name string // 工作表显示名(尽力解析,失败为空)
Algorithm string // "SHA-512" 等;旧式 16 位哈希为空
Salt []byte
Hash []byte
SpinCount int
Legacy string // 旧式 16 位哈希(password 属性,如 "CEA4")
}
func (p Protection) isSHA() bool { return p.Algorithm != "" && len(p.Salt) > 0 && len(p.Hash) > 0 }
func (p Protection) label() string {
if p.Name != "" {
return fmt.Sprintf("%s (%s)", p.File, p.Name)
}
return p.File
}
func main() {
workers := Workers
if workers <= 0 {
workers = runtime.NumCPU()
}
data, err := os.ReadFile(XlsxPath)
if err != nil {
fatalf("cannot read xlsx %q: %v", XlsxPath, err)
}
prots, err := parseProtections(data)
if err != nil {
fatalf("parse protections: %v", err)
}
if len(prots) == 0 {
fatalf("no <sheetProtection> found in %s (nothing to crack)", XlsxPath)
}
fmt.Printf("File: %s\n", XlsxPath)
fmt.Println("Protected sheets:")
for _, p := range prots {
if p.isSHA() {
fmt.Printf(" - %-22s %s spinCount=%d salt=%s\n",
p.label(), p.Algorithm, p.SpinCount,
base64.StdEncoding.EncodeToString(p.Salt))
} else {
fmt.Printf(" - %-22s legacy 16-bit hash password=%q (可直接删标签解锁;无法还原原始密码)\n",
p.label(), p.Legacy)
}
}
fmt.Println()
// 选择目标 SHA-512 工作表。
target := pickTarget(prots)
if target == nil {
fmt.Println("没有 SHA-512 保护的工作表。旧式 16 位哈希的工作表无法“还原原始密码”")
fmt.Println("(同一哈希有海量碰撞),但可以直接删除 <sheetProtection> 标签解锁——")
fmt.Println("这类保护并不加密数据,见下方说明。")
return
}
shaSheets := filterSHA(prots)
fmt.Printf("目标 / Target: %s spinCount=%d\n", target.label(), target.SpinCount)
fmt.Printf("其它同类工作表 %d 个;若共用同一密码,破出即可全部解锁。\n\n", len(shaSheets)-1)
if InfoOnly {
return
}
v := &Verifier{salt: target.Salt, target: target.Hash, spin: target.SpinCount}
// 免费顺手检查:空密码。
if v.Check(utf16leString("")) {
fmt.Println("==> 该工作表的保护密码是【空】。直接在 Excel 里点“撤销保护”不输密码即可。")
return
}
start := time.Now()
// ---------- 阶段一:字典 ----------
if WordlistPath != "" {
fmt.Printf("[字典] %s ...\n", WordlistPath)
if pw, ok := tryWordlist(WordlistPath, v, workers); ok {
success(pw, shaSheets, start)
return
}
fmt.Println("[字典] 未命中。")
}
if !DoBruteForce {
fmt.Println("DoBruteForce=false,结束。")
return
}
// ---------- 阶段二:暴力枚举 ----------
charset := buildCharset(UseDigits, UseLower, UseUpper, UseSpecial, SpecialChars)
if len(charset) == 0 {
fatalf("空字符集:请至少启用 UseDigits/UseLower/UseUpper/UseSpecial 之一")
}
minLen, maxLen := MinPasswordLength, MaxPasswordLength
if minLen < 1 {
minLen = 1
}
fmt.Printf("Charset: %d chars: %s\n", len(charset), previewCharset(charset))
fmt.Printf("Lengths: %d..%d Workers: %d\n", minLen, maxLen, workers)
fmt.Printf("Search space: %s combinations\n", totalCombos(len(charset), minLen, maxLen))
fmt.Printf("估算耗时(约 %d 候选/秒):%s\n\n", estRate(workers),
estDuration(len(charset), minLen, maxLen, estRate(workers)))
cr := newCracker(v, charset, workers)
stop := make(chan struct{})
go cr.report(stop, start)
for L := minLen; L <= maxLen; L++ {
if pw, ok := cr.crackLength(L); ok {
close(stop)
fmt.Printf("\r%-70s\r", "")
success(pw, shaSheets, start)
return
}
}
close(stop)
fmt.Printf("\r%-70s\r", "")
fmt.Printf("已穷尽长度 %d..%d(%d 字符集),未找到。尝试 %d 次,用时 %s。\n",
minLen, maxLen, len(charset), atomic.LoadUint64(&cr.total),
time.Since(start).Round(time.Second))
fmt.Println("建议:加大长度/字符集,或改用字典(WordlistPath)。")
}
func success(pw string, shaSheets []*Protection, start time.Time) {
fmt.Printf("\n*** 找到密码 / PASSWORD FOUND: %q ***\n", pw)
fmt.Printf("用时 %s\n", time.Since(start).Round(time.Millisecond))
// 验证这个密码对哪些工作表有效。
pwb := utf16leString(pw)
var ok, no []string
for _, p := range shaSheets {
v := &Verifier{salt: p.Salt, target: p.Hash, spin: p.SpinCount}
if v.Check(pwb) {
ok = append(ok, p.label())
} else {
no = append(no, p.label())
}
}
fmt.Printf("适用于这些 SHA-512 工作表: %s\n", strings.Join(ok, ", "))
if len(no) > 0 {
fmt.Printf("对这些工作表不适用(密码不同): %s\n", strings.Join(no, ", "))
}
}
// ---------------------------------------------------------------------------
// 目标选择 / target selection
// ---------------------------------------------------------------------------
func filterSHA(prots []Protection) []*Protection {
var out []*Protection
for i := range prots {
if prots[i].isSHA() {
out = append(out, &prots[i])
}
}
return out
}
func pickTarget(prots []Protection) *Protection {
sha := filterSHA(prots)
if len(sha) == 0 {
return nil
}
if TargetSheet == "" {
return sha[0]
}
want := strings.TrimSuffix(TargetSheet, ".xml")
for _, p := range sha {
if strings.TrimSuffix(p.File, ".xml") == want {
return p
}
}
fatalf("TargetSheet=%q 不是 SHA-512 保护的工作表;可选:%s", TargetSheet, shaNames(sha))
return nil
}
func shaNames(sha []*Protection) string {
var n []string
for _, p := range sha {
n = append(n, strings.TrimSuffix(p.File, ".xml"))
}
return strings.Join(n, ", ")
}
// ---------------------------------------------------------------------------
// 验证器 / Verifier —— 已验证的 Excel SHA-512 算法
// ---------------------------------------------------------------------------
type Verifier struct {
salt []byte
target []byte
spin int
}
// Check 传入 UTF-16LE 编码的密码字节,返回是否匹配。
func (v *Verifier) Check(pwUTF16 []byte) bool {
h := sha512.New()
h.Write(v.salt)
h.Write(pwUTF16)
hash := h.Sum(nil)
var it [4]byte
for i := 0; i < v.spin; i++ {
binary.LittleEndian.PutUint32(it[:], uint32(i))
h.Reset()
h.Write(hash)
h.Write(it[:])
hash = h.Sum(nil)
}
return bytes.Equal(hash, v.target)
}
func utf16leString(s string) []byte {
u := utf16.Encode([]rune(s))
out := make([]byte, len(u)*2)
for i, c := range u {
out[2*i] = byte(c)
out[2*i+1] = byte(c >> 8)
}
return out
}
// ---------------------------------------------------------------------------
// 字典攻击 / wordlist
// ---------------------------------------------------------------------------
func tryWordlist(path string, v *Verifier, workers int) (string, bool) {
f, err := os.Open(path)
if err != nil {
fatalf("cannot open wordlist %q: %v", path, err)
}
defer f.Close()
lines := make(chan string, 4096)
var found int32
var result string
var mu sync.Mutex
var tried uint64
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for w := range lines {
if atomic.LoadInt32(&found) != 0 {
return
}
if v.Check(utf16leString(w)) {
mu.Lock()
result = w
mu.Unlock()
atomic.StoreInt32(&found, 1)
return
}
atomic.AddUint64(&tried, 1)
}
}()
}
// 读文件喂给 worker。
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 64*1024), 4*1024*1024) // 容纳较长的行
go func() {
for sc.Scan() {
if atomic.LoadInt32(&found) != 0 {
break
}
lines <- sc.Text()
}
close(lines)
}()
wg.Wait()
if atomic.LoadInt32(&found) != 0 {
return result, true
}
return "", false
}
// ---------------------------------------------------------------------------
// 暴力枚举引擎 / brute-force engine(结构同 PDF 版)
// ---------------------------------------------------------------------------
type cracker struct {
v *Verifier
charset []byte
workers int
total uint64
curLen int32
}
func newCracker(v *Verifier, charset []byte, workers int) *cracker {
return &cracker{v: v, charset: charset, workers: workers}
}
// crackLength 枚举所有长度恰为 L 的密码,按首字符分片给各 worker。
func (c *cracker) crackLength(L int) (string, bool) {
atomic.StoreInt32(&c.curLen, int32(L))
base := len(c.charset)
var (
nextTask int64 = -1
found int32
result string
resMu sync.Mutex
wg sync.WaitGroup
)
for id := 0; id < c.workers; id++ {
wg.Add(1)
go func() {
defer wg.Done()
u := make([]byte, 2*L) // UTF-16LE 缓冲,逐位更新
idx := make([]int, L)
var local uint64
flush := func() {
if local > 0 {
atomic.AddUint64(&c.total, local)
local = 0
}
}
for {
if atomic.LoadInt32(&found) != 0 {
flush()
return
}
t := int(atomic.AddInt64(&nextTask, 1))
if t >= base {
flush()
return
}
// 初始化里程表 / init odometer.
u[0] = c.charset[t]
u[1] = 0
idx[0] = t
for p := 1; p < L; p++ {
idx[p] = 0
u[2*p] = c.charset[0]
u[2*p+1] = 0
}
for {
if c.v.Check(u) {
resMu.Lock()
result = utf16leToString(u)
resMu.Unlock()
atomic.StoreInt32(&found, 1)
flush()
return
}
local++
if local >= 64 {
flush()
if atomic.LoadInt32(&found) != 0 {
return
}
}
// 里程表进位 / increment positions L-1..1.
p := L - 1
for ; p >= 1; p-- {
idx[p]++
if idx[p] < base {
u[2*p] = c.charset[idx[p]]
break
}
idx[p] = 0
u[2*p] = c.charset[0]
}
if p < 1 {
break // 本首字符任务枚举完
}
}
}
}()
}
wg.Wait()
if atomic.LoadInt32(&found) != 0 {
return result, true
}
return "", false
}
func (c *cracker) report(stop <-chan struct{}, start time.Time) {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
var last uint64
lastT := start
for {
select {
case <-stop:
return
case now := <-ticker.C:
total := atomic.LoadUint64(&c.total)
dt := now.Sub(lastT).Seconds()
rate := float64(total-last) / dt
last, lastT = total, now
fmt.Printf("\r[len %d] tried %-12d %7.0f/s elapsed %s ",
atomic.LoadInt32(&c.curLen), total, rate,
time.Since(start).Round(time.Second))
}
}
}
func utf16leToString(u []byte) string {
pts := make([]uint16, len(u)/2)
for i := range pts {
pts[i] = uint16(u[2*i]) | uint16(u[2*i+1])<<8
}
return string(utf16.Decode(pts))
}
// ---------------------------------------------------------------------------
// xlsx 解析 / parsing
// ---------------------------------------------------------------------------
var (
reProt = regexp.MustCompile(`<sheetProtection[^>]*?/?>`)
reAlgo = regexp.MustCompile(`algorithmName="([^"]*)"`)
reHash = regexp.MustCompile(`hashValue="([^"]*)"`)
reSalt = regexp.MustCompile(`saltValue="([^"]*)"`)
reSpin = regexp.MustCompile(`spinCount="([^"]*)"`)
reLegacy = regexp.MustCompile(`password="([^"]*)"`)
reSheetF = regexp.MustCompile(`xl/worksheets/(sheet\d+\.xml)$`)
)
func parseProtections(data []byte) ([]Protection, error) {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, err
}
names := sheetDisplayNames(zr) // file -> 显示名(尽力)
var out []Protection
for _, zf := range zr.File {
m := reSheetF.FindStringSubmatch(zf.Name)
if m == nil {
continue
}
file := m[1]
body, err := readZipFile(zf)
if err != nil {
continue
}
tag := reProt.Find(body)
if tag == nil {
continue
}
p := Protection{File: file, Name: names[file]}
if mm := reAlgo.FindSubmatch(tag); mm != nil {
p.Algorithm = string(mm[1])
}
if mm := reHash.FindSubmatch(tag); mm != nil {
p.Hash, _ = base64.StdEncoding.DecodeString(string(mm[1]))
}
if mm := reSalt.FindSubmatch(tag); mm != nil {
p.Salt, _ = base64.StdEncoding.DecodeString(string(mm[1]))
}
if mm := reSpin.FindSubmatch(tag); mm != nil {
p.SpinCount, _ = strconv.Atoi(string(mm[1]))
}
// 旧式 password 属性只在没有 hashValue 时才当作 legacy。
if p.Hash == nil {
if mm := reLegacy.FindSubmatch(tag); mm != nil {
p.Legacy = string(mm[1])
}
}
out = append(out, p)
}
sort.Slice(out, func(i, j int) bool { return out[i].File < out[j].File })
return out, nil
}
// sheetDisplayNames 尽力把 sheetN.xml 映射到工作表显示名。
func sheetDisplayNames(zr *zip.Reader) map[string]string {
res := map[string]string{}
var wbBody, relBody []byte
for _, zf := range zr.File {
switch {
case strings.HasSuffix(zf.Name, "xl/workbook.xml"):
wbBody, _ = readZipFile(zf)
case strings.HasSuffix(zf.Name, "xl/_rels/workbook.xml.rels"):
relBody, _ = readZipFile(zf)
}
}
if wbBody == nil || relBody == nil {
return res
}
// rId -> sheetN.xml
relRe := regexp.MustCompile(`<Relationship\b[^>]*>`)
ridRe := regexp.MustCompile(`Id="([^"]*)"`)
tgtRe := regexp.MustCompile(`Target="([^"]*)"`)
rid2file := map[string]string{}
for _, r := range relRe.FindAll(relBody, -1) {
id := ridRe.FindSubmatch(r)
tg := tgtRe.FindSubmatch(r)
if id == nil || tg == nil {
continue
}
t := string(tg[1])
if i := strings.LastIndex(t, "worksheets/"); i >= 0 {
rid2file[string(id[1])] = t[i+len("worksheets/"):]
}
}
// <sheet name=".." r:id=".."/>
sheetRe := regexp.MustCompile(`<sheet\b[^>]*>`)
nameRe := regexp.MustCompile(`name="([^"]*)"`)
sridRe := regexp.MustCompile(`r:id="([^"]*)"`)
for _, s := range sheetRe.FindAll(wbBody, -1) {
nm := nameRe.FindSubmatch(s)
id := sridRe.FindSubmatch(s)
if nm == nil || id == nil {
continue
}
if file, ok := rid2file[string(id[1])]; ok {
res[file] = string(nm[1])
}
}
return res
}
func readZipFile(zf *zip.File) ([]byte, error) {
rc, err := zf.Open()
if err != nil {
return nil, err
}
defer rc.Close()
var buf bytes.Buffer
if _, err := buf.ReadFrom(rc); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// ---------------------------------------------------------------------------
// 字符集 + 辅助 / charset + helpers
// ---------------------------------------------------------------------------
func buildCharset(digits, lower, upper, special bool, specialChars string) []byte {
var sb strings.Builder
if digits {
sb.WriteString(digitsSet)
}
if lower {
sb.WriteString(lowerSet)
}
if upper {
sb.WriteString(upperSet)
}
if special {
sb.WriteString(specialChars)
}
seen := make(map[byte]bool, sb.Len())
out := make([]byte, 0, sb.Len())
for _, ch := range []byte(sb.String()) {
if !seen[ch] {
seen[ch] = true
out = append(out, ch)
}
}
return out
}
func previewCharset(cs []byte) string {
s := string(cs)
if len(s) > 70 {
return s[:70] + "..."
}
return s
}
func totalCombos(base, min, max int) string {
sum := big.NewInt(0)
b := big.NewInt(int64(base))
term := new(big.Int).Exp(b, big.NewInt(int64(min)), nil)
for L := min; L <= max; L++ {
sum.Add(sum, term)
term.Mul(term, b)
}
return sum.String()
}
// estRate 粗略估计每秒候选数(每核约 38/s,本机实测)。
func estRate(workers int) int {
return workers * 38
}
func estDuration(base, min, max, rate int) string {
if rate <= 0 {
return "n/a"
}
sum := big.NewInt(0)
b := big.NewInt(int64(base))
term := new(big.Int).Exp(b, big.NewInt(int64(min)), nil)
for L := min; L <= max; L++ {
sum.Add(sum, term)
term.Mul(term, b)
}
secs := new(big.Int).Div(sum, big.NewInt(int64(rate)))
d := time.Duration(secs.Int64()) * time.Second
if !secs.IsInt64() || d < 0 {
return "极长(>数百年,请缩小范围或用字典)"
}
switch {
case d < time.Minute:
return d.Round(time.Second).String()
case d < 48*time.Hour:
return d.Round(time.Minute).String()
default:
return fmt.Sprintf("%.1f 天", d.Hours()/24)
}
}
func fatalf(format string, args ...any) {
fmt.Fprintf(os.Stderr, "error: "+format+"\n", args...)
os.Exit(1)
}