summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore8
-rw-r--r--LICENSE22
-rw-r--r--README.md119
-rw-r--r--go.mod10
-rw-r--r--go.sum77
-rw-r--r--main.go281
6 files changed, 517 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0079875
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+# Binaries
+yubisigner-cli
+*.exe
+*.out
+
+# Test files
+*.sig
+test*.txt
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d5d2872
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2024 Stefan Claas (original yubisigner)
+Copyright (c) 2026 Gab Virebent (CLI extraction)
+
+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:
+
+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.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..773dc35
--- /dev/null
+++ b/README.md
@@ -0,0 +1,119 @@
+# yubisigner-cli
+
+Command-line version of [yubisigner](https://github.com/Ch1ffr3punk/yubisigner) by Stefan Claas, for signing files with YubiKey PIV Ed25519 keys.
+
+## What is this?
+
+This is a CLI tool extracted from the original yubisigner GUI application. It provides the same cryptographic signing functionality but in a command-line interface suitable for scripting and automation.
+
+## Why CLI?
+
+The original yubisigner is a Fyne GUI application. To integrate YubiKey PIV signing with automated workflows like NeoMutt mail2news posting, a CLI version was needed.
+
+## How it was created
+
+This tool was created by extracting the core signing logic from the original `yubisigner.go`:
+
+### Extracted functions (with original line references)
+
+| Function | Original lines | Purpose |
+|----------|---------------|---------|
+| `normalizeToCRLF` | 538-544 | RFC-compliant line ending normalization |
+| `ensureUTF8` | 547-552 | UTF-8 validation and sanitization |
+| `calculateHashesRAM` | 1621-1640 | Calculate 4 hashes (RIPEMD-256, SHA-256, SM3, Streebog-256) |
+| `formatHashes` | 1746-1766 | Format hashes with right-aligned names |
+| `formatSignatureRFC` | 1996-2007 | Format signature with 64-char line breaks |
+| `openYubiKey` | 2073-2092 | Open YubiKey at specified index |
+| `signEd25519Data` | 1843-1862 | Sign data with Ed25519 (PIV slot 9c) |
+| `signDataInternal` | 1769-1840 | Main signing workflow (Ed25519 only) |
+
+### Constants preserved
+
+- `Ed25519SignatureSize`, `Ed25519PublicKeySize`, `Ed25519CombinedSize` (lines 95-99)
+- `AlgorithmED25519` (lines 69-73)
+
+### Changes from original
+
+1. **GUI removed**: All Fyne GUI code stripped out
+2. **Ed25519 only**: Only Ed25519 support (original supports ECDSA/RSA too)
+3. **CLI flags**: Added flag parsing for command-line arguments
+4. **No PKCS#11**: Direct YubiKey PIV access only (no PKCS#11 smartcard support)
+5. **Simplified output**: Direct signature file write (no GUI dialogs)
+
+The core cryptographic logic is **exactly the same** as the original yubisigner. All signing functions are verbatim copies with comments indicating source line numbers.
+
+## Requirements
+
+- Go 1.21+
+- YubiKey with PIV Ed25519 key in slot 9c (Signature slot)
+- Dependencies:
+ - `github.com/go-piv/piv-go/v2/piv`
+ - `github.com/c0mm4nd/go-ripemd`
+ - `github.com/martinlindhe/gogost/gost34112012256`
+ - `github.com/tjfoc/gmsm/sm3`
+
+## Build
+
+```bash
+go build -o yubisigner-cli main.go
+```
+
+## Usage
+
+```bash
+yubisigner-cli \
+ --input <file> \
+ --author "Your Name" \
+ --email "you@example.com" \
+ --url "https://example.com" \
+ --comment "Optional comment"
+```
+
+Output: `<file>.sig` (detached signature)
+
+### Optional arguments
+
+- `--email` (default: "n/a")
+- `--url` (default: "n/a")
+- `--telefax` (default: "n/a")
+- `--comment` (default: "n/a")
+- `--pin` (PIN will be prompted if not provided)
+- `--output` (default: `<input>.sig`)
+
+## Signature format
+
+Identical to original yubisigner:
+
+```
+Author: Gab Virebent
+Signed at: 2026-05-30 23:15:00 +0000
+Filename: message.txt
+File size: 1234 bytes
+Email: gabriel1@virebent.art
+Telefax: n/a
+URL: https://contact.virebent.art
+Comment: Posted via NeoMutt mail2news
+RIPEMD-256: abc123...
+ SHA-256: def456...
+ SM3: 789abc...
+Streebog-256: fedcba...
+-----BEGIN YUBISIGNER ED25519 SIGNATURE-----
+0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
+...
+-----END YUBISIGNER ED25519 SIGNATURE-----
+```
+
+## Integration with NeoMutt
+
+See [neomutt-config](https://git.virebent.art/virebent/neomutt-config) for mail2news integration with automatic YubiKey signing via the `vim-yubisigner` wrapper.
+
+## License
+
+MIT (same as original yubisigner)
+
+## Credits
+
+- **Stefan Claas** ([@Ch1ffr3punk](https://github.com/Ch1ffr3punk)): Original yubisigner GUI application
+- **Gab Virebent**: CLI extraction for automation workflows
+
+All cryptographic logic is Stefan's work. This is purely a CLI wrapper around his signing implementation.
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..6165fcd
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,10 @@
+module yubisigner-cli
+
+go 1.23
+
+require (
+ github.com/c0mm4nd/go-ripemd v0.0.0-20200326052756-bd1759ad7d10
+ github.com/go-piv/piv-go/v2 v2.5.0
+ github.com/martinlindhe/gogost v0.0.0-20170914195721-31862914ae20
+ github.com/tjfoc/gmsm v1.4.1
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..19cc3d6
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,77 @@
+cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
+github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
+github.com/c0mm4nd/go-ripemd v0.0.0-20200326052756-bd1759ad7d10 h1:wJ2csnFApV9G1jgh5KmYdxVOQMi+fihIggVTjcbM7ts=
+github.com/c0mm4nd/go-ripemd v0.0.0-20200326052756-bd1759ad7d10/go.mod h1:mYPR+a1fzjnHY3VFH5KL3PkEjMlVfGXP7c8rbWlkLJg=
+github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
+github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
+github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
+github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
+github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
+github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
+github.com/go-piv/piv-go/v2 v2.5.0 h1:w4KZ3GytEGZt8zm+S7olcIHZk0giL23xVqCa2HgwuqA=
+github.com/go-piv/piv-go/v2 v2.5.0/go.mod h1:ShZi74nnrWNQEdWzRUd/3cSig3uNOcEZp+EWl0oewnI=
+github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
+github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
+github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
+github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
+github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
+github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
+github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
+github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
+github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
+github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
+github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/martinlindhe/gogost v0.0.0-20170914195721-31862914ae20 h1:NgvNvoe91W36nQwPNvM8KSyvN7Tgfrp1gGhNqp6iuK8=
+github.com/martinlindhe/gogost v0.0.0-20170914195721-31862914ae20/go.mod h1:QWtANgYYeIaHYj7lc8bygiTdXt3t3bQHH6ObdVMIC2s=
+github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
+github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
+github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
+golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
+golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
+golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
+golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
+golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
+golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
+google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
+google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
+google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
+google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
+google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
+google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
+google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
+google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
+google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
+google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
+google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
+google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
+honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..23dcef6
--- /dev/null
+++ b/main.go
@@ -0,0 +1,281 @@
+package main
+
+import (
+ "crypto"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/c0mm4nd/go-ripemd"
+ "github.com/go-piv/piv-go/v2/piv"
+ "github.com/martinlindhe/gogost/gost34112012256"
+ "github.com/tjfoc/gmsm/sm3"
+)
+
+// Ed25519 constants (EXACTLY from yubisigner.go:95-99)
+const (
+ Ed25519SignatureSize = 64
+ Ed25519PublicKeySize = 32
+ Ed25519CombinedSize = Ed25519SignatureSize + Ed25519PublicKeySize
+)
+
+// Algorithm constant (EXACTLY from yubisigner.go:69-73)
+const (
+ AlgorithmED25519 = "ED25519"
+)
+
+// normalizeToCRLF converts any line ending to RFC-compliant CRLF (EXACTLY from yubisigner.go:538-544)
+func normalizeToCRLF(data []byte) []byte {
+ s := string(data)
+ s = strings.ReplaceAll(s, "\r\n", "\n")
+ s = strings.ReplaceAll(s, "\r", "\n")
+ s = strings.ReplaceAll(s, "\n", "\r\n")
+ return []byte(s)
+}
+
+// ensureUTF8 ensures the string is valid UTF-8 (EXACTLY from yubisigner.go:547-552)
+func ensureUTF8(s string) string {
+ if utf8.ValidString(s) {
+ return s
+ }
+ return strings.ToValidUTF8(s, " ")
+}
+
+// calculateHashesRAM calculates all hashes for files that fit in RAM (EXACTLY from yubisigner.go:1621-1640)
+func calculateHashesRAM(data []byte) map[string]string {
+ hashes := make(map[string]string)
+
+ gostHasher := gost34112012256.New()
+ gostHasher.Write(data)
+ hashes["Streebog-256"] = hex.EncodeToString(gostHasher.Sum(nil))
+
+ ripemdHasher := ripemd.New256()
+ ripemdHasher.Write(data)
+ hashes["RIPEMD-256"] = hex.EncodeToString(ripemdHasher.Sum(nil))
+
+ sha256Hash := sha256.Sum256(data)
+ hashes["SHA-256"] = hex.EncodeToString(sha256Hash[:])
+
+ sm3Hasher := sm3.New()
+ sm3Hasher.Write(data)
+ hashes["SM3"] = hex.EncodeToString(sm3Hasher.Sum(nil))
+
+ return hashes
+}
+
+// formatHashes formats hashes with right-aligned names (EXACTLY from yubisigner.go:1746-1766)
+func formatHashes(hashes map[string]string) string {
+ keys := make([]string, 0, len(hashes))
+ for k := range hashes {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+
+ maxLen := 0
+ for _, k := range keys {
+ if len(k) > maxLen {
+ maxLen = len(k)
+ }
+ }
+
+ var result strings.Builder
+ for _, k := range keys {
+ paddedKey := fmt.Sprintf("%*s", maxLen, k)
+ result.WriteString(fmt.Sprintf("%s: %s\r\n", paddedKey, hashes[k]))
+ }
+ return result.String()
+}
+
+// formatSignatureRFC formats signature in RFC-compliant format with line breaks (EXACTLY from yubisigner.go:1996-2007)
+func formatSignatureRFC(sig string) string {
+ var result strings.Builder
+ for i := 0; i < len(sig); i += 64 {
+ end := i + 64
+ if end > len(sig) {
+ end = len(sig)
+ }
+ result.WriteString(sig[i:end])
+ result.WriteString("\r\n")
+ }
+ return result.String()
+}
+
+// openYubiKey opens YubiKey at specified index (EXACTLY from yubisigner.go:2073-2092)
+func openYubiKey(index int) (*piv.YubiKey, error) {
+ cards, err := piv.Cards()
+ if err != nil {
+ return nil, fmt.Errorf("failed to list cards: %v", err)
+ }
+ if len(cards) == 0 {
+ return nil, fmt.Errorf("no smart card found")
+ }
+
+ count := 0
+ for _, card := range cards {
+ if strings.Contains(strings.ToLower(card), "yubikey") {
+ if count == index {
+ return piv.Open(card)
+ }
+ count++
+ }
+ }
+ return nil, fmt.Errorf("no YubiKey found at index %d", index)
+}
+
+// signEd25519Data handles Ed25519 signing (EXACTLY from yubisigner.go:1843-1862)
+func signEd25519Data(pin string, hash []byte, pubKey ed25519.PublicKey, yk *piv.YubiKey) (string, string, error) {
+ auth := piv.KeyAuth{PIN: pin}
+ priv, err := yk.PrivateKey(piv.SlotSignature, pubKey, auth)
+ if err != nil {
+ return "", "", fmt.Errorf("failed to get private key: %v", err)
+ }
+
+ signer, ok := priv.(crypto.Signer)
+ if !ok {
+ return "", "", fmt.Errorf("key does not implement crypto.Signer")
+ }
+
+ signature, err := signer.Sign(rand.Reader, hash, crypto.Hash(0))
+ if err != nil {
+ return "", "", fmt.Errorf("Ed25519 signing failed: %v", err)
+ }
+
+ combined := append(pubKey, signature...)
+ return hex.EncodeToString(combined), AlgorithmED25519, nil
+}
+
+// signDataInternal performs the actual signing operation with YubiKey (EXACTLY from yubisigner.go:1769-1840, Ed25519 only)
+func signDataInternal(pin, data []byte) (string, string, error) {
+ yk, err := openYubiKey(0)
+ if err != nil {
+ return "", "", err
+ }
+ defer yk.Close()
+
+ cert, err := yk.Certificate(piv.SlotSignature)
+ if err != nil {
+ return "", "", fmt.Errorf("failed to get certificate from signature slot: %v", err)
+ }
+
+ ed25519PubKey, ok := cert.PublicKey.(ed25519.PublicKey)
+ if !ok {
+ return "", "", fmt.Errorf("public key is not Ed25519 (this CLI tool only supports Ed25519)")
+ }
+
+ hash := sha256.Sum256(data)
+ return signEd25519Data(string(pin), hash[:], ed25519PubKey, yk)
+}
+
+func main() {
+ var (
+ inputFile string
+ author string
+ email string
+ url string
+ telefax string
+ comment string
+ pin string
+ outputFile string
+ )
+
+ flag.StringVar(&inputFile, "input", "", "File to sign (required)")
+ flag.StringVar(&author, "author", "", "Author name (required)")
+ flag.StringVar(&email, "email", "n/a", "Email address (optional)")
+ flag.StringVar(&url, "url", "n/a", "URL (optional)")
+ flag.StringVar(&telefax, "telefax", "n/a", "Telefax (optional)")
+ flag.StringVar(&comment, "comment", "n/a", "Comment (optional)")
+ flag.StringVar(&pin, "pin", "", "YubiKey PIN (will prompt if not provided)")
+ flag.StringVar(&outputFile, "output", "", "Output signature file (default: <input>.sig)")
+ flag.Parse()
+
+ // Validate required fields
+ if inputFile == "" {
+ fmt.Fprintln(os.Stderr, "Error: --input is required")
+ flag.Usage()
+ os.Exit(1)
+ }
+ if author == "" {
+ fmt.Fprintln(os.Stderr, "Error: --author is required")
+ flag.Usage()
+ os.Exit(1)
+ }
+
+ // Ensure UTF-8 (EXACTLY from yubisigner.go:1010, 1120)
+ author = ensureUTF8(author)
+ if comment != "n/a" {
+ comment = ensureUTF8(comment)
+ }
+
+ // Read input file
+ data, err := os.ReadFile(inputFile)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error reading file: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Get file info
+ fileInfo, err := os.Stat(inputFile)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error getting file info: %v\n", err)
+ os.Exit(1)
+ }
+ fileSize := fileInfo.Size()
+
+ // Calculate hashes (EXACTLY from yubisigner.go:1103)
+ fmt.Println("Calculating hashes...")
+ hashes := calculateHashesRAM(data)
+
+ // Prepare metadata (EXACTLY from yubisigner.go:1124-1132)
+ metadata := fmt.Sprintf("Author: %s\r\n", author)
+ metadata += fmt.Sprintf("Signed at: %s\r\n", time.Now().UTC().Format("2006-01-02 15:04:05 +0000"))
+ metadata += fmt.Sprintf("Filename: %s\r\n", filepath.Base(inputFile))
+ metadata += fmt.Sprintf("File size: %d bytes\r\n", fileSize)
+ metadata += fmt.Sprintf("Email: %s\r\n", email)
+ metadata += fmt.Sprintf("Telefax: %s\r\n", telefax)
+ metadata += fmt.Sprintf("URL: %s\r\n", url)
+ metadata += fmt.Sprintf("Comment: %s\r\n", comment)
+ metadata += formatHashes(hashes)
+
+ // Get PIN if not provided
+ if pin == "" {
+ fmt.Print("Enter YubiKey PIN: ")
+ fmt.Scanln(&pin)
+ }
+
+ // Sign metadata (EXACTLY from yubisigner.go:1138)
+ fmt.Println("Signing with YubiKey (touch required)...")
+ sig, algo, err := signDataInternal([]byte(pin), []byte(metadata))
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Signing failed: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Build result (EXACTLY from yubisigner.go:1144-1148)
+ result := metadata
+ result += "-----BEGIN YUBISIGNER " + algo + " SIGNATURE-----\r\n"
+ result += formatSignatureRFC(sig)
+ result += "-----END YUBISIGNER " + algo + " SIGNATURE-----\r\n"
+
+ // Determine output file
+ if outputFile == "" {
+ outputFile = inputFile + ".sig"
+ }
+
+ // Write signature file
+ err = os.WriteFile(outputFile, []byte(result), 0644)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error writing signature: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("✓ File signed successfully: %s\n", outputFile)
+}