certificate-api/routes/pgp.go

80 lines
2.0 KiB
Go

package routes
import (
"encoding/hex"
"net/http"
"time"
"io/ioutil"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
"golang.org/x/crypto/openpgp/packet"
"github.com/gin-gonic/gin"
)
type PGPKey struct {
FullName, Name, Comment, Email string
CreationTime time.Time
PublicKeyAlgorithm packet.PublicKeyAlgorithm
Fingerprint [20]byte
KeyID uint16
}
func GetOpenPGPInformationEncoded(c *gin.Context) {
query := c.Copy().Request.Body
query2 := c.Copy().Request.Body
body, _ := ioutil.ReadAll(query2)
block, err := armor.Decode(query)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": false,
"message": "Unable to parse body.",
})
return
}
pkt := packet.NewReader(block.Body)
entity, err := openpgp.ReadEntity(pkt)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": false,
"message": "Unable to parse body.",
})
return
}
if len(entity.Identities) > 1 {
c.JSON(http.StatusBadRequest, gin.H{
"status": false,
"message": "No identities found in PGP key.",
})
return
}
var key *PGPKey
for name, identity := range entity.Identities {
key = &PGPKey{
FullName: name,
Name: identity.UserId.Name,
Comment: identity.UserId.Comment,
Email: identity.UserId.Email,
CreationTime: entity.PrimaryKey.CreationTime,
PublicKeyAlgorithm: entity.PrimaryKey.PubKeyAlgo,
Fingerprint: entity.PrimaryKey.Fingerprint,
KeyID: uint16(entity.PrimaryKey.KeyId),
}
break
}
c.JSON(http.StatusOK, gin.H{
"status": true,
"fullName": key.FullName,
"name": key.Name,
"comment": key.Comment,
"email": key.Email,
"creationTime": key.CreationTime,
"publicKeyAlgorithm": key.PublicKeyAlgorithm,
"fingerprint": hex.EncodeToString(key.Fingerprint[:]),
"keyID": key.KeyID,
"armor": body,
})
}