Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Beginning of a Go version of github.com/open-eid/libdigidoc #69

Draft
wants to merge 18 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions digidogo/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package main

import (
"archive/zip"
"crypto/x509"
"io/ioutil"
"log"
"mime"
"os"
"path"
"regexp"

"github.com/beevik/etree"
dsig "github.com/russellhaering/goxmldsig"
)

func main() {
inputName := os.Args[1]
mimetype := mime.TypeByExtension(inputName)
if mimetype == "" {
mimetype = map[string]string{
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
}[path.Ext(inputName)]
}

// Generate a key and self-signed certificate for signing
randomKeyStore := dsig.RandomKeyStoreForTest()
ctx := dsig.NewDefaultSigningContext(randomKeyStore)
_, cert, err := randomKeyStore.GetKeyPair()
if err != nil {
panic(err)
}
root, err := x509.ParseCertificate(cert)
if err != nil {
panic(err)
}
validCtx := dsig.NewDefaultValidationContext(&dsig.MemoryX509CertificateStore{
Roots: []*x509.Certificate{root},
})

// Sign the element
input, err := ioutil.ReadFile(os.Args[1])
if err != nil {
panic(err)
}

signedElement, err := ctx.SignXAdES(path.Base(inputName), mimetype, input)
if err != nil {
panic(err)
}
if _, err := validCtx.Validate(signedElement); err != nil {
log.Fatal("Failed Validation: ", err)
panic(err)
}

doc := etree.NewDocument()
doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8" standalone="no"`)
doc.SetRoot(signedElement)

edoc, err := os.Create(
string(regexp.MustCompile("\\.[^\\.]+$").ReplaceAll(
[]byte(inputName), []byte(".edoc"),
)),
)
if err != nil {
panic(err)
}
w := zip.NewWriter(edoc)

mimetypeFile, err := w.Create("mimetype")
if err != nil {
panic(err)
}
mimetypeFile.Write([]byte("application/vnd.etsi.asic-e+zip"))

{
f, err := w.Create("META-INF/manifest.xml")
if err != nil {
panic(err)
}

root := etree.NewDocument()
root.CreateProcInst("xml", `version="1.0" encoding="UTF-8" standalone="no"`)
manifest := root.CreateElement("manifest")
manifest.Space = "manifest"
manifest.Attr = append(manifest.Attr, etree.Attr{
Space: "xmlns",
Key: "manifest",
Value: "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0",
})

manifest.Attr = append(manifest.Attr, etree.Attr{
Space: "manifest",
Key: "version",
Value: "1.2",
})

entry := manifest.CreateElement("file-entry")
entry.Space = "manifest"
entry.Attr = append(entry.Attr, etree.Attr{
Space: "manifest",
Key: "full-path",
Value: "/",
})
entry.Attr = append(entry.Attr, etree.Attr{
Space: "manifest",
Key: "media-type",
Value: "application/vnd.etsi.asic-e+zip",
})

fileEntry := manifest.CreateElement("file-entry")
fileEntry.Space = "manifest"
fileEntry.Attr = append(fileEntry.Attr, etree.Attr{
Space: "manifest",
Key: "full-path",
Value: path.Base(inputName),
})
fileEntry.Attr = append(fileEntry.Attr, etree.Attr{
Space: "manifest",
Key: "media-type",
Value: mimetype,
})

output, err := root.WriteToString()
println(output)
if err != nil {
panic(err)
}
f.Write([]byte(output))
}

edocSigns, err := w.Create("META-INF/edoc-signatures-S1.xml")
if err != nil {
panic(err)
}
str, err := doc.WriteToString()
if err != nil {
panic(err)
}
println(str)
edocSigns.Write([]byte(str))

f, err := w.Create(path.Base(inputName))
if err != nil {
panic(err)
}
f.Write(input)

if err := w.Close(); err != nil {
log.Fatal(err)
}
if err := edoc.Close(); err != nil {
log.Fatal(err)
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ require (
github.com/beevik/etree v1.1.0
github.com/jonboulle/clockwork v0.2.0
github.com/stretchr/testify v1.6.1
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83
)
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
Expand Down
60 changes: 60 additions & 0 deletions rfc3161/timestamp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package rfc3161

import (
"bytes"
"encoding/base64"
"io/ioutil"
"net/http"
)

const (
TsaFreeTsa = "http://freetsa.org/tsr"
TsaCertum = "http://time.certum.pl"
TsaComodora = "http://timestamp.comodoca.com/rfc3161"
)

func TimestampRequest(data []byte, url string) (*http.Request, error) {
req, err := http.NewRequest(
http.MethodPost,
url,
bytes.NewBuffer(data),
)
if err != nil {
return nil, err
}

req.Header.Set("Content-Type", "application/timestamp-query")
req.Header.Set("Accept", "application/timestamp-reply")
req.Header.Set("Connection", "Close")
req.Header.Set("Cache-Control", "no-cache")

return req, nil
}

func TimestampResponse(data []byte, url string) (*http.Response, error) {
req, err := TimestampRequest(data, url)
if err != nil {
return nil, err
}

res, err := http.DefaultClient.Do(req)

return res, err
}

func Timestamp(data []byte, url string) (*string, error) {
res, err := TimestampResponse(data, url)
if err != nil {
return nil, err
}

defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}

encoded := base64.StdEncoding.EncodeToString(body)

return &encoded, nil
}
40 changes: 40 additions & 0 deletions rfc3161/timestamp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package rfc3161

import (
"encoding/base64"
"io/ioutil"
"testing"
)

func TestTimestampResponse(t *testing.T) {
type args struct {
data []byte
url string
}
tests := []struct {
name string
args args
want int
wantErr bool
}{
{"Empty", args{[]byte(""), TsaFreeTsa}, 200, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := TimestampResponse(tt.args.data, tt.args.url)
if (err != nil) != tt.wantErr {
t.Errorf("TimestampResponse() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got.StatusCode != tt.want {
t.Errorf("TimestampResponse() = %v, want %v", got, tt.want)
}
body, err := ioutil.ReadAll(got.Body)
if tt.want == 200 && err != nil {
t.Error(err)
} else if tt.want == 200 {
t.Error(base64.StdEncoding.EncodeToString(body))
}
})
}
}
Loading