Friday, October 28, 2022

[SOLVED] how to convert dsa PublicKey to PEM Files use golang

Issue

  • 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))

}

Solution

i follow java of sun from

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
}



Answered By - 田伯成
Answer Checked By - Mildred Charles (WPSolving Admin)