forked from RobotsAndPencils/go-saml
-
Notifications
You must be signed in to change notification settings - Fork 2
/
xmlsec.go
71 lines (57 loc) · 1.41 KB
/
xmlsec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package saml
import (
"crypto/x509"
"encoding/pem"
"errors"
"io/ioutil"
"github.com/ma314smith/signedxml"
)
// Sign creates a signature for an XML document and returns it
func Sign(xml string, privateKeyPath string) (string, error) {
pemString, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
return "", err
}
pemBlock, _ := pem.Decode([]byte(pemString))
if pemBlock == nil {
return "", errors.New("Count not parse private key")
}
key, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
if err != nil {
return "", err
}
signer, err := signedxml.NewSigner(xml)
if err != nil {
return "", err
}
samlSignedRequestXML, err := signer.Sign(key)
if err != nil {
return "", err
}
return samlSignedRequestXML, nil
}
// Verify validates the signature of an XML document
func Verify(xml string, publicCertPath string) ([]string, error) {
pemString, err := ioutil.ReadFile(publicCertPath)
if err != nil {
return nil, err
}
pemBlock, _ := pem.Decode([]byte(pemString))
if pemBlock == nil {
return nil, errors.New("Could not parse certificate")
}
cert, err := x509.ParseCertificate(pemBlock.Bytes)
if err != nil {
return nil, err
}
validator, err := signedxml.NewValidator(xml)
if err != nil {
return nil, err
}
validator.Certificates = append(validator.Certificates, *cert)
xmlRef, err := validator.ValidateReferences()
if err != nil {
return nil, err
}
return xmlRef, nil
}