chore: support convert age-secret-key to age-public-key for build-in age tool

This commit is contained in:
wwqgtxx committed 2026-06-03 16:15:02 +08:00
1 parent 316f5df1f1
commit b60e687eb7
3 files changed
+45 -1

No files matched your search

+31 -1
View File
@@ -68,6 +68,18 @@ func EncryptBytes(data []byte, recipients ...Recipient) ([]byte, error) {
return buf.Bytes(), nil
}
// ConvertToRecipient convert age.Identity to age.Recipient
func ConvertToRecipient(identity Identity) (Recipient, error) {
switch identity := identity.(type) {
case *age.X25519Identity:
return identity.Recipient(), nil
case *age.HybridIdentity:
return identity.Recipient(), nil
default:
return nil, fmt.Errorf("unexpected identity type: %T", identity)
}
}
func GenX25519KeyPair() (string, string, error) {
identity, err := age.GenerateX25519Identity()
if err != nil {
@@ -86,7 +98,7 @@ func GenHybridKeyPair() (string, string, error) {
func Main(args []string) {
if len(args) < 1 {
panic("Using: age keygen/keygen-pq/decrypt/encrypt")
panic("Using: age keygen/keygen-pq/convert/decrypt/encrypt")
}
switch args[0] {
case "keygen":
@@ -105,6 +117,24 @@ func Main(args []string) {
fmt.Printf("# created: %s\n", time.Now().Format(time.RFC3339))
fmt.Printf("# public key: %s\n", publicKey)
fmt.Printf("%s\n", secretKey)
case "convert":
if len(args) < 1 {
panic("Using: age convert <secret_key>")
}
identities, err := ParseIdentities(args[1])
if err != nil {
panic(err)
}
if len(identities) == 0 {
panic("no identities found in the input")
}
for _, identity := range identities {
recipient, err := ConvertToRecipient(identity)
if err != nil {
panic(err)
}
fmt.Println(recipient)
}
case "decrypt":
if len(args) < 3 {
panic("Using: age decrypt <secret_key> <source_file> <target_file>")
+13
View File
@@ -1,6 +1,7 @@
package age_test
import (
"fmt"
"testing"
"github.com/metacubex/mihomo/component/age"
@@ -30,6 +31,18 @@ func TestAge(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(identities) != len(recipients) {
t.Fatal("identities and recipients are not equal")
}
for i, identity := range identities {
recipient, err := age.ConvertToRecipient(identity)
if err != nil {
t.Fatal(err)
}
if fmt.Sprint(recipient) != fmt.Sprint(recipients[i]) {
t.Fatal("recipient is not equal to recipients: ", recipient, " != ", recipients[i], "")
}
}
rawData := []byte("hello world")
encryptData, err := age.EncryptBytes(rawData, recipients...)
if err != nil {
+1
View File
@@ -1478,6 +1478,7 @@ proxy-providers:
# # 实用工具:
# # 您可以通过 "mihomo age keygen" 生成符合要求的 x25519 key
# # 您可以通过 "mihomo age keygen-pq" 生成符合要求的 mlkem768-x25519 key
# # 您可以通过 "mihomo age convert <secret_key>" 从 age-secret-key 导出 age-public-key
# # 您可以通过 "mihome age decrypt <secret_key> <source_file> <target_file>" 将已加密文件解密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
# # 您可以通过 "mihome age encrypt <public_key> <source_file> <target_file>" 将未加密文件加密,<source_file> 为 - 时会从标准输入读取,<target_file> 为 - 时会往标准输出写入
# # 参考实现: