如何使用Golang将DSA公钥转换为PEM文件?

huangapple go评论82阅读模式
英文:

how to convert dsa PublicKey to PEM Files use golang

问题

当我使用RSA PEM字符串时,下面的代码可以正常工作,生成RSA公钥对象并重新生成RSA PEM字符串。

当我使用DSA PEM字符串时,下面的代码无法正常工作,只能生成DSA公钥对象。

> x509: unsupported public key type: *dsa.PublicKey

我想知道如何使DSA公钥对象重新生成DSA PEM字符串。

这是我的代码:

package main

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"os"
)

var rsaBytes = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyQubwvMR1ctRTTylCJ9u
imYlIMo8rkOXV8S7NaRB2pdEoeG1RiGVanTKwu1N6D7CNbXV+o+QVOpSB823iTb+
kxHaTpGcJwVvA1K3pJOgSSAx3bbr8Ekv1FXNZ3bGFOrzoD0OOWICDGnNQznQ8cJ8
+EFwjLBoqqqWM892BkGQuQTRLEmjrFOrLlTB99yXMeiD4c2iQFCtNZHpFviS9ahp
Irb/sEyhs2hFYqUUByZQQqo0ewv8MFiHGXG68t2LMnTkbff3KyUxgChEPiqAUNAb
LJ1JaFwypZdHr7KyJqatCIOk2m1Yz3umnW/KsM0Q+N9C4UZdn6GbZyStELGBJjsv
aQIDAQAB
-----END PUBLIC KEY-----`

var dsaBytes = `-----BEGIN PUBLIC KEY-----
MIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9E
AMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f
6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv
8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtc
NrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwky
jMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/h
WuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAIb9o0KPsjAdzjK571e1Mx7ZhEyJ
GrcxHiN2sW8IztEbqrKKiMxpNlTwm234uBdtzVHE3uDWZpfHPMIRmwBjCYDFRowW
WVRdhdFXZlpCyp1gMWqJ11dh3FI3+O43DevRSyyuLRVCNQ1J3iVgwY5ndRpZU7n6
y8DPH4/4EBT7KvnV
-----END PUBLIC KEY-----`

func main() {
	// pemBlock, _ := pem.Decode([]byte(rsaBytes))
	pemBlock, _ := pem.Decode([]byte(dsaBytes))

	pubInterface, err := x509.ParsePKIXPublicKey(pemBlock.Bytes)
	pubkeyByte, err := x509.MarshalPKIXPublicKey(pubInterface)
	if err != nil {
		fmt.Println(err)
		os.Exit(0)
	}
	block := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubkeyByte,
	}
	pemByte := pem.EncodeToMemory(block)
	fmt.Println(string(pemByte))

}
英文:
  • when i use an rsa pem string the follow code can work fine, generate to rsa public key object and regenerate to rsa pem string
  • when i use an dsa pem string the follow code can not work fine, only can generate to dsa public key object

> x509: unsupported public key type: *dsa.PublicKey

i want to konw how to make dsa public key object regenerate dsa pem string

this is my code

package main

import (
	"C"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"os"
)

var rsaBytes = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyQubwvMR1ctRTTylCJ9u
imYlIMo8rkOXV8S7NaRB2pdEoeG1RiGVanTKwu1N6D7CNbXV+o+QVOpSB823iTb+
kxHaTpGcJwVvA1K3pJOgSSAx3bbr8Ekv1FXNZ3bGFOrzoD0OOWICDGnNQznQ8cJ8
+EFwjLBoqqqWM892BkGQuQTRLEmjrFOrLlTB99yXMeiD4c2iQFCtNZHpFviS9ahp
Irb/sEyhs2hFYqUUByZQQqo0ewv8MFiHGXG68t2LMnTkbff3KyUxgChEPiqAUNAb
LJ1JaFwypZdHr7KyJqatCIOk2m1Yz3umnW/KsM0Q+N9C4UZdn6GbZyStELGBJjsv
aQIDAQAB
-----END PUBLIC KEY-----`

var dsaBytes = `-----BEGIN PUBLIC KEY-----
MIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9E
AMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f
6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv
8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtc
NrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwky
jMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/h
WuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAIb9o0KPsjAdzjK571e1Mx7ZhEyJ
GrcxHiN2sW8IztEbqrKKiMxpNlTwm234uBdtzVHE3uDWZpfHPMIRmwBjCYDFRowW
WVRdhdFXZlpCyp1gMWqJ11dh3FI3+O43DevRSyyuLRVCNQ1J3iVgwY5ndRpZU7n6
y8DPH4/4EBT7KvnV
-----END PUBLIC KEY-----`

func main() {
	// pemBlock, _ := pem.Decode([]byte(rsaBytes))
	pemBlock, _ := pem.Decode([]byte(dsaBytes))

	pubInterface, err := x509.ParsePKIXPublicKey(pemBlock.Bytes)
	pubkeyByte, err := x509.MarshalPKIXPublicKey(pubInterface)
	if err != nil {
		fmt.Println(err)
		os.Exit(0)
	}
	block := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubkeyByte,
	}
	pemByte := pem.EncodeToMemory(block)
	fmt.Println(string(pemByte))

}

答案1

得分: 1

我遵循来自Sun的Java代码:

org.bouncycastle.jce.provider.JDKDSAPublicKey
org.bouncycastle.asn1.x509.SubjectPublicKeyInfo

package transform

import (
	"crypto/dsa"
	"encoding/base64"
	"encoding/pem"
)

func getDsaPem(publicKey *dsa.PublicKey) string {
	p := publicKey.P.Bytes()
	if publicKey.P.BitLen()/8+1 > len(p) {
		p = append([]byte{0}, p...)
	}

	q := publicKey.Q.Bytes()
	if publicKey.Q.BitLen()/8+1 > len(q) {
		q = append([]byte{0}, q...)
	}

	g := publicKey.G.Bytes()
	if publicKey.G.BitLen()/8+1 > len(g) {
		g = append([]byte{0}, g...)
	}

	y := publicKey.Y.Bytes()
	if publicKey.Y.BitLen()/8+1 > len(y) {
		y = append([]byte{0}, y...)
	}

	p = (&SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(p).Data
	q = (&SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(q).Data
	g = (&SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(g).Data
	y = (&SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(y).Data

	params := append(p, append(q, g...)...)
	paramData := &SunDerOutputStream{Data: make([]byte, 0)}
	paramData.write(48, params)
	oidAndParams := paramData.sunPutOID().Data
	publicKeyBodyData := &SunDerOutputStream{Data: make([]byte, 0)}
	publicKeyBodyData.write(48, oidAndParams)

	publicKeyBodyData.sunPutUnalignedBitString(y)
	publicKeyData := &SunDerOutputStream{Data: make([]byte, 0)}
	publicKeyData.write(48, publicKeyBodyData.Data)

	block := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: publicKeyData.Data,
	}
	pubkeyByte := pem.EncodeToMemory(block)
	return string(pubkeyByte)
}

type SunDerOutputStream struct {
	Data []byte
}

func (s *SunDerOutputStream) write(dataItem byte, data []byte) *SunDerOutputStream {
	s.Data = append(s.Data, dataItem)
	s.sunPutLength(len(data))
	s.Data = append(s.Data, data...)
	return s
}

func (s *SunDerOutputStream) sunPutOID() *SunDerOutputStream {
	// OID 1.2.840.10040.4.1
	oid, _ := base64.StdEncoding.DecodeString("BgcqhkjOOAQB")
	s.Data = append(oid, s.Data...)
	return s
}

func (s *SunDerOutputStream) sunPutInteger(data []byte) *SunDerOutputStream {
	s.Data = append(s.Data, 2)
	s.sunPutLength(len(data))
	s.Data = append(s.Data, data...)
	return s
}

func (s *SunDerOutputStream) sunPutLength(lenData int) *SunDerOutputStream {
	if lenData < 128 {
		s.Data = append(s.Data, []byte{byte(lenData)}...)
	} else if lenData < 256 {
		s.Data = append(s.Data, []byte{129, byte(lenData)}...)
	} else if lenData < 65536 {
		s.Data = append(s.Data, []byte{130, byte(lenData >> 8), byte(lenData)}...)
	}
	return s
}

func (s *SunDerOutputStream) sunPutUnalignedBitString(data []byte) *SunDerOutputStream {
	s.Data = append(s.Data, 3)
	s.sunPutLength(len(data) + 1)
	s.Data = append(s.Data, 0)
	s.Data = append(s.Data, data...)
	return s
}
英文:

i follow java of sun from

org.bouncycastle.jce.provider.JDKDSAPublicKey
org.bouncycastle.asn1.x509.SubjectPublicKeyInfo

package transform
import (
&quot;crypto/dsa&quot;
&quot;encoding/base64&quot;
&quot;encoding/pem&quot;
)
func getDsaPem(publicKey *dsa.PublicKey) string {
p := publicKey.P.Bytes()
if publicKey.P.BitLen()/8+1 &gt; len(p) {
p = append([]byte{0}, p...)
}
q := publicKey.Q.Bytes()
if publicKey.Q.BitLen()/8+1 &gt; len(q) {
q = append([]byte{0}, q...)
}
g := publicKey.G.Bytes()
if publicKey.G.BitLen()/8+1 &gt; len(g) {
g = append([]byte{0}, g...)
}
y := publicKey.Y.Bytes()
if publicKey.Y.BitLen()/8+1 &gt; len(y) {
y = append([]byte{0}, y...)
}
p = (&amp;SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(p).Data
q = (&amp;SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(q).Data
g = (&amp;SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(g).Data
y = (&amp;SunDerOutputStream{Data: make([]byte, 0)}).sunPutInteger(y).Data
params := append(p, append(q, g...)...)
paramData := &amp;SunDerOutputStream{Data: make([]byte, 0)}
paramData.write(48, params)
oidAndParams := paramData.sunPutOID().Data
publicKeyBodyData := &amp;SunDerOutputStream{Data: make([]byte, 0)}
publicKeyBodyData.write(48, oidAndParams)
publicKeyBodyData.sunPutUnalignedBitString(y)
publicKeyData := &amp;SunDerOutputStream{Data: make([]byte, 0)}
publicKeyData.write(48, publicKeyBodyData.Data)
block := &amp;pem.Block{
Type:  &quot;PUBLIC KEY&quot;,
Bytes: publicKeyData.Data,
}
pubkeyByte := pem.EncodeToMemory(block)
return string(pubkeyByte)
}
type SunDerOutputStream struct {
Data []byte
}
func (s *SunDerOutputStream) write(dataItem byte, data []byte) *SunDerOutputStream {
s.Data = append(s.Data, dataItem)
s.sunPutLength(len(data))
s.Data = append(s.Data, data...)
return s
}
func (s *SunDerOutputStream) sunPutOID() *SunDerOutputStream {
// OID 1.2.840.10040.4.1
oid, _ := base64.StdEncoding.DecodeString(&quot;BgcqhkjOOAQB&quot;)
s.Data = append(oid, s.Data...)
return s
}
func (s *SunDerOutputStream) sunPutInteger(data []byte) *SunDerOutputStream {
s.Data = append(s.Data, 2)
s.sunPutLength(len(data))
s.Data = append(s.Data, data...)
return s
}
func (s *SunDerOutputStream) sunPutLength(lenData int) *SunDerOutputStream {
if lenData &lt; 128 {
s.Data = append(s.Data, []byte{byte(lenData)}...)
} else if lenData &lt; 256 {
s.Data = append(s.Data, []byte{129, byte(lenData)}...)
} else if lenData &lt; 65536 {
s.Data = append(s.Data, []byte{130, byte(lenData &gt;&gt; 8), byte(lenData)}...)
}
return s
}
func (s *SunDerOutputStream) sunPutUnalignedBitString(data []byte) *SunDerOutputStream {
s.Data = append(s.Data, 3)
s.sunPutLength(len(data) + 1)
s.Data = append(s.Data, 0)
s.Data = append(s.Data, data...)
return s
}

答案2

得分: 0

以下是x509包中MarshalPKIXPublicKey函数的注释:

// MarshalPKIXPublicKey将公钥转换为PKIX、ASN.1 DER格式。
// 编码的公钥是一个SubjectPublicKeyInfo结构
// (参见RFC 5280,第4.1节)。
//
// 目前支持以下类型的密钥:*rsa.PublicKey、*ecdsa.PublicKey
// 和ed25519.PublicKey。不支持的密钥类型会导致错误。
//
// 这种类型的密钥通常以“PUBLIC KEY”类型的PEM块进行编码。

您还可以在包文档中获取相同的信息:
https://pkg.go.dev/crypto/x509#MarshalPKIXPublicKey

所以您在Go 1.19中需要的内容是不可用的。

如果您不想自己编写DSA私钥的ASN1编码,我想使用OpenSSL的DSA函数可能更简单。
https://www.mkssoftware.com/docs/man1/openssl_dsa.1.asp

英文:

Below is the comment of MarshalPKIXPublicKey function in x509 package:

// MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
// The encoded public key is a SubjectPublicKeyInfo structure
// (see RFC 5280, Section 4.1).
//
// The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
// and ed25519.PublicKey. Unsupported key types result in an error.
//
// This kind of key is commonly encoded in PEM blocks of type &quot;PUBLIC KEY&quot;.

You can also get the same information on the package documentation:
https://pkg.go.dev/crypto/x509#MarshalPKIXPublicKey

So what you need is not available in Go 1.19.

If you don't want to code yourself the ASN1 encoding of DSA private keys, I suppose the simpler is to use Openssl dsa function.
https://www.mkssoftware.com/docs/man1/openssl_dsa.1.asp

huangapple
  • 本文由 发表于 2022年8月5日 16:03:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/73246538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定