Skip to content

Commit

Permalink
fix: parse pcks8 private key issue (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
shipengqi authored Aug 26, 2023
1 parent dc19c24 commit a3c204a
Show file tree
Hide file tree
Showing 13 changed files with 224 additions and 11 deletions.
6 changes: 6 additions & 0 deletions .github/workflows/codeql.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@ name: "codeql"
on:
push:
branches: [ main ]
paths-ignore:
- 'docs/**'
- 'README.md'
pull_request:
branches: [ main ]
paths-ignore:
- 'docs/**'
- 'README.md'
jobs:
analyze:
name: analyze
Expand Down
6 changes: 6 additions & 0 deletions .github/workflows/gitleaks.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ on:
push:
branches: ['main']
tags: ['v*']
paths-ignore:
- 'docs/**'
- 'README.md'
pull_request:
paths-ignore:
- 'docs/**'
- 'README.md'
permissions:
contents: read
jobs:
Expand Down
6 changes: 6 additions & 0 deletions .github/workflows/grype.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ on:
push:
branches: ['main']
tags: ['v*']
paths-ignore:
- 'docs/**'
- 'README.md'
pull_request:
paths-ignore:
- 'docs/**'
- 'README.md'
jobs:
scan-source:
name: scan-source
Expand Down
6 changes: 6 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ on:
- v*
branches:
- main
paths-ignore:
- 'docs/**'
- 'README.md'
pull_request:
paths-ignore:
- 'docs/**'
- 'README.md'
permissions:
contents: read

Expand Down
7 changes: 6 additions & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ name: test
on:
push:
branches: [ main ]
paths-ignore:
- 'docs/**'
- 'README.md'
pull_request:
branches: [ main ]

paths-ignore:
- 'docs/**'
- 'README.md'
jobs:
unit-test:
runs-on: ubuntu-latest
Expand Down
153 changes: 153 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,159 @@ Common libraries for Go.
[![Release](https://img.shields.io/github/release/shipengqi/golib.svg)](https://github.com/shipengqi/golib/releases)
[![License](https://img.shields.io/github/license/shipengqi/golib)](https://github.com/shipengqi/golib/blob/main/LICENSE)

## Getting Started

```go
package main

import (
"context"
"errors"
"fmt"
"os"
"time"

"github.com/shipengqi/golib/cliutil"
"github.com/shipengqi/golib/convutil"
"github.com/shipengqi/golib/crtutil"
"github.com/shipengqi/golib/crtutil/tmpl"
"github.com/shipengqi/golib/cryptoutil/xsha256"
"github.com/shipengqi/golib/fsutil"
"github.com/shipengqi/golib/netutil"
"github.com/shipengqi/golib/retry"
"github.com/shipengqi/golib/strutil"
"github.com/shipengqi/golib/sysutil"
)

func main() {
// --------------------------------------
// cliutil Examples

// retrieve value of the given flag from args.
cliutil.RetrieveFlag(os.Args, "--name", "-n")

// execute the given command.
output, _ := cliutil.ExecContext(context.TODO(), "/bin/sh", "-c", "ls -l")
fmt.Println(output)

// execute the given command with a pipe.
pipecmd := "echo 1;echo 2;echo 3;echo 4"
var lines []string
_ = cliutil.ExecPipe(context.TODO(), func(line []byte) {
lines = append(lines, string(line))
}, "/bin/sh", "-c", pipecmd)
fmt.Println(lines)
// output like the following:
// [1, 2, 3, 4]

// --------------------------------------
// convutil Examples

// convert []byte to string.
output = convutil.B2S([]byte("abc")) // output: "abc"
// convert string to []byte.
_ = convutil.S2B("abc")

// --------------------------------------
// crtutil Examples

// read certificate file
x509Crt, _ := crtutil.ReadAsX509FromFile("server.crt")

// converts a slice of x509.Certificate into PEM block, in the order they are passed.
pemData, _ := crtutil.EncodeX509ChainToPEM(x509Crt, nil)

// read private key file
pkey, _ := crtutil.ReadAsSignerFromFile("server.key")

// output certificate content using the default template
outputb, _ := tmpl.BuildDefaultCertTemplate(x509Crt[0], true)
fmt.Println(outputb)
// output like the following:
// Serial: 5577006791947779410
// Valid: 2022-09-23 06:09 UTC to 2032-09-30 06:09 UTC
// Signature: SHA256-RSA (self-signed)
// BitLength: 4096
// Subject Key ID: 6D:E9:2B:2B:1D:59:AB:B5:46:8C:7B:93:C3:49:7E:95:B0:20:E5:4C
// Basic Constraints: CA:true, pathlen:-1


// --------------------------------------
// cryptoutil Examples

// encrypts string with SHA256 algorithms.
output = xsha256.Encrypt("Hello, World!")
fmt.Println(output) // dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f


// --------------------------------------
// fsutil Examples

// copies a file or directory from src to dst.
_ = fsutil.Copy("testdata/src", "testdata/dst")

// create a new archive.
_ = fsutil.Tar("testdata/src", "testdata/dst.tar")

// extract all files from an archive.
_ = fsutil.UnTar("testdata/dst.tar", "testdata/src")

// like Tar but will use gzip to compress.
_ = fsutil.Compress("testdata/src", "testdata/dst.tgz")

// like UnTar but will use gzip to decompress.
_ = fsutil.DeCompress("testdata/dst.tgz", "testdata/src")

// --------------------------------------
// netutil Examples

num := netutil.IPString2Uint("16.187.191.122")
fmt.Println(num) // 280739706

// --------------------------------------
// retry Examples

var count int
_ = retry.Times(5).WithInterval(time.Second).Do(func() error {
count++
return nil
})
fmt.Println(count) // 1

count = 0
_ = retry.Times(5).WithInterval(time.Second).Do(func() error {
count++
return errors.New("test err")
})
fmt.Println(count) // 5

// --------------------------------------
// strutil Examples

// check if str1 contains str2 ignoring case sensitivity
contains := strutil.ContainsIgnoreCase("STR", "str")
fmt.Println(contains) // true

// like strings.ContainsAny but does an "only" instead of "any".
// If all characters in s are found in chars, the function returns true.
contains = strutil.ContainsOnly("234234", "0123456789")
fmt.Println(contains) // true

// --------------------------------------
// sysutil Examples

// returns home directory of current user.
homedir := sysutil.HomeDir()

// retrieves the value of the environment variable named
// by the key
v := sysutil.EnvOr("TEST_ENV_KEY", "default-value")

// returns the FQDN of current node.
fqdn, _ := sysutil.FQDN()
}
```

## Documentation

You can find the docs at [go docs](https://pkg.go.dev/github.com/shipengqi/golib).
Expand Down
13 changes: 8 additions & 5 deletions crtutil/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package crtutil

import (
"crypto"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
Expand Down Expand Up @@ -62,19 +64,20 @@ func readAsSigner(key, keypass []byte, isBase64 bool) (crypto.PrivateKey, error)
return pkcs1, nil
}

var eck *ecdsa.PrivateKey
if eck, err = x509.ParseECPrivateKey(keyBytes); err == nil {
return eck, nil
}

var pkcs8 interface{}
if pkcs8, err = x509.ParsePKCS8PrivateKey(keyBytes); err == nil {
switch pkcs8k := pkcs8.(type) {
case *rsa.PrivateKey, *ecdsa.PrivateKey:
case *rsa.PrivateKey, *ecdsa.PrivateKey, *ecdh.PrivateKey, ed25519.PrivateKey:
return pkcs8k, nil
default:
return nil, ErrUnknownKeyType
}
}

var eck *ecdsa.PrivateKey
if eck, err = x509.ParseECPrivateKey(keyBytes); err == nil {
return eck, nil
}
return nil, err
}
2 changes: 1 addition & 1 deletion fsutil/tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func Tar(src, dst string) error {
return tarf(fw, src)
}

// UnTar Extract all files from an archive.
// UnTar extract all files from an archive.
func UnTar(src, dst string) (err error) {
fr, err := os.Open(src)
if err != nil {
Expand Down
5 changes: 3 additions & 2 deletions strutil/str.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ func ContainsIgnoreCase(str1, str2 string) bool {
}

// ContainsOnly like strings.ContainsAny but does an only instead of any.
func ContainsOnly(s string, comp string) bool {
// If all characters in s are found in chars, the function returns true.
func ContainsOnly(s string, chars string) bool {
return strings.IndexFunc(s, func(r rune) bool {
return !strings.ContainsRune(comp, r)
return !strings.ContainsRune(chars, r)
}) == -1
}

Expand Down
13 changes: 12 additions & 1 deletion sysutil/sys.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func User() *user.User {
return u
}

// FQDN returns the FQDN of current.
// FQDN returns the FQDN of current node.
func FQDN() (string, error) {
return fqdn()
}
Expand Down Expand Up @@ -78,3 +78,14 @@ func IsBigEndian() bool {
func TmpDir() string {
return os.TempDir()
}

// EnvOr retrieves the value of the environment variable named
// by the key. If the variable is present in the environment the
// value (which may be empty) is returned.
// Otherwise, the default value will be returned.
func EnvOr(key, def string) string {
if v, ok := os.LookupEnv(key); ok {
return v
}
return def
}
14 changes: 14 additions & 0 deletions sysutil/sys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ func TestTmpDir(t *testing.T) {
assert.NotEmpty(t, got)
}

func TestEnvOr(t *testing.T) {
testEnvKey := "TEST_ENV_KEY"
testEnvValue := "test"
unknownEnvKey := "UNKNOWN_ENV_KEY"
unknownEnvValue := "unknown"
err := os.Setenv(testEnvKey, testEnvValue)
assert.NoError(t, err)
got := EnvOr(testEnvKey, "")
assert.Equal(t, testEnvValue, got)

got = EnvOr(unknownEnvKey, unknownEnvValue)
assert.Equal(t, unknownEnvValue, got)
}

func isci() bool {
if os.Getenv("CI") == "true" {
return true
Expand Down
2 changes: 1 addition & 1 deletion sysutil/sys_unix.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// +build linux darwin
//go:build linux || darwin

package sysutil

Expand Down
2 changes: 2 additions & 0 deletions sysutil/sys_unix_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//go:build linux || darwin

package sysutil

import (
Expand Down

0 comments on commit a3c204a

Please sign in to comment.