2018-10-07 23:07:43 +00:00
|
|
|
package dhparam
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/asn1"
|
|
|
|
"encoding/pem"
|
2024-09-20 07:55:10 +00:00
|
|
|
"errors"
|
2023-02-10 15:45:24 +00:00
|
|
|
"fmt"
|
2018-10-07 23:07:43 +00:00
|
|
|
"math/big"
|
|
|
|
)
|
|
|
|
|
2024-09-20 07:55:10 +00:00
|
|
|
// ErrNoPem is returned if pemData for the Decode function is nil or empty.
|
|
|
|
var ErrNoPem = errors.New("empty or nil bytes for PEM data")
|
|
|
|
|
|
|
|
// ErrInvalidPem is returned if pemData for the Decode function does not seem to be PEM-encoded data.
|
|
|
|
var ErrInvalidPem = errors.New("invalid bytes for PEM data; does not seem to be PEM-encoded")
|
|
|
|
|
2018-10-07 23:07:43 +00:00
|
|
|
// DH contains a prime (P) and a generator (G) number representing the DH parameters
|
|
|
|
type DH struct {
|
|
|
|
P *big.Int
|
|
|
|
G int
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decode reads a DH parameters struct from its PEM data
|
|
|
|
func Decode(pemData []byte) (*DH, error) {
|
2024-09-20 07:55:10 +00:00
|
|
|
if pemData == nil || len(pemData) == 0 {
|
|
|
|
return nil, ErrNoPem
|
|
|
|
}
|
|
|
|
|
2018-10-07 23:07:43 +00:00
|
|
|
blk, _ := pem.Decode(pemData)
|
2024-09-20 07:55:10 +00:00
|
|
|
if blk == nil {
|
|
|
|
return nil, ErrInvalidPem
|
|
|
|
}
|
2018-10-07 23:07:43 +00:00
|
|
|
|
|
|
|
out := &DH{}
|
|
|
|
if _, err := asn1.Unmarshal(blk.Bytes, out); err != nil {
|
2023-02-10 15:45:24 +00:00
|
|
|
return nil, fmt.Errorf("could not unmarshal ASN1: %w", err)
|
2018-10-07 23:07:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return out, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ToPEM encodes the DH parameters using ASN1 and PEM encoding
|
|
|
|
func (d DH) ToPEM() ([]byte, error) {
|
|
|
|
data, err := asn1.Marshal(d)
|
|
|
|
if err != nil {
|
2023-02-10 15:45:24 +00:00
|
|
|
return nil, fmt.Errorf("unable to marshal ASN1 data: %w", err)
|
2018-10-07 23:07:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
err = pem.Encode(buf, &pem.Block{
|
|
|
|
Type: pemHeader,
|
|
|
|
Bytes: data,
|
|
|
|
})
|
|
|
|
|
|
|
|
return buf.Bytes(), err
|
|
|
|
}
|