import template code
This commit is contained in:
27
pkg/client/auth.go
Normal file
27
pkg/client/auth.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type AuthCredential struct {
|
||||
Payload map[string]string
|
||||
}
|
||||
|
||||
func NewAuthCredential(username, password string) *AuthCredential {
|
||||
payload := make(map[string]string)
|
||||
payload["username"] = username
|
||||
payload["password"] = password
|
||||
return &AuthCredential{
|
||||
Payload: payload,
|
||||
}
|
||||
}
|
||||
|
||||
func (cred *AuthCredential) GetRequestMetadata(ctx context.Context, data ...string) (map[string]string, error) {
|
||||
var err error
|
||||
return cred.Payload, err
|
||||
}
|
||||
|
||||
func (cred *AuthCredential) RequireTransportSecurity() bool {
|
||||
return false
|
||||
}
|
||||
38
pkg/client/client.go
Normal file
38
pkg/client/client.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"helmet/pkg/mlbctl"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultServicePort uint32 = 1027
|
||||
)
|
||||
|
||||
func NewClient(hostinfo string, authCred *AuthCredential) (*grpc.ClientConn, mlbctl.ControlClient, error) {
|
||||
var err error
|
||||
var cli mlbctl.ControlClient
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
const idleTimeout time.Duration = 30 * time.Second
|
||||
dialOpts := []grpc.DialOption{
|
||||
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
|
||||
grpc.WithPerRPCCredentials(authCred),
|
||||
grpc.WithBlock(),
|
||||
grpc.WithIdleTimeout(idleTimeout),
|
||||
}
|
||||
conn, err := grpc.NewClient(hostinfo, dialOpts...)
|
||||
if err != nil {
|
||||
return conn, cli, fmt.Errorf("Dial error: %v", err)
|
||||
}
|
||||
cli = mlbctl.NewControlClient(conn)
|
||||
return conn, cli, err
|
||||
}
|
||||
49
pkg/client/refer.go
Normal file
49
pkg/client/refer.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Referer struct {
|
||||
urlobj *url.URL
|
||||
user, pass string
|
||||
obj, oper string
|
||||
}
|
||||
|
||||
func NewReferer(hostname string) (*Referer, error) {
|
||||
ref := &Referer{}
|
||||
if !strings.Contains(hostname, "://") {
|
||||
hostname = "https://" + hostname
|
||||
}
|
||||
urlobj, err := url.Parse(hostname)
|
||||
if err != nil {
|
||||
return ref, err
|
||||
}
|
||||
if urlobj.User != nil {
|
||||
ref.user = urlobj.User.Username()
|
||||
ref.pass, _ = urlobj.User.Password()
|
||||
urlobj.User = nil
|
||||
}
|
||||
ref.urlobj = urlobj
|
||||
if !strings.Contains(ref.urlobj.Host, ":") {
|
||||
portstr := strconv.FormatInt(int64(DefaultServicePort), 10)
|
||||
ref.urlobj.Host = ref.urlobj.Host + ":" + portstr
|
||||
}
|
||||
return ref, err
|
||||
}
|
||||
|
||||
func (ref *Referer) Hostinfo() string {
|
||||
return ref.urlobj.Host
|
||||
}
|
||||
|
||||
func (ref *Referer) Userinfo() (string, string) {
|
||||
return ref.user, ref.pass
|
||||
}
|
||||
|
||||
func (ref *Referer) SetUserinfo(user, pass string) {
|
||||
if user != "" && pass != "" {
|
||||
ref.user, ref.pass = user, pass
|
||||
}
|
||||
}
|
||||
170
pkg/mlbctl/mlbctl.pb.go
Normal file
170
pkg/mlbctl/mlbctl.pb.go
Normal file
@@ -0,0 +1,170 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.5
|
||||
// protoc v3.21.12
|
||||
// source: mlbctl.proto
|
||||
|
||||
package mlbctl
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type GetHelloParams struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetHelloParams) Reset() {
|
||||
*x = GetHelloParams{}
|
||||
mi := &file_mlbctl_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetHelloParams) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetHelloParams) ProtoMessage() {}
|
||||
|
||||
func (x *GetHelloParams) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_mlbctl_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetHelloParams.ProtoReflect.Descriptor instead.
|
||||
func (*GetHelloParams) Descriptor() ([]byte, []int) {
|
||||
return file_mlbctl_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
type GetHelloResult struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetHelloResult) Reset() {
|
||||
*x = GetHelloResult{}
|
||||
mi := &file_mlbctl_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetHelloResult) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetHelloResult) ProtoMessage() {}
|
||||
|
||||
func (x *GetHelloResult) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_mlbctl_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetHelloResult.ProtoReflect.Descriptor instead.
|
||||
func (*GetHelloResult) Descriptor() ([]byte, []int) {
|
||||
return file_mlbctl_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *GetHelloResult) GetMessage() string {
|
||||
if x != nil {
|
||||
return x.Message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_mlbctl_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_mlbctl_proto_rawDesc = string([]byte{
|
||||
0x0a, 0x0c, 0x6d, 0x6c, 0x62, 0x63, 0x74, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06,
|
||||
0x6d, 0x6c, 0x62, 0x63, 0x74, 0x6c, 0x22, 0x10, 0x0a, 0x0e, 0x67, 0x65, 0x74, 0x48, 0x65, 0x6c,
|
||||
0x6c, 0x6f, 0x50, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x2a, 0x0a, 0x0e, 0x67, 0x65, 0x74, 0x48,
|
||||
0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65,
|
||||
0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73,
|
||||
0x73, 0x61, 0x67, 0x65, 0x32, 0x47, 0x0a, 0x07, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x12,
|
||||
0x3c, 0x0a, 0x08, 0x67, 0x65, 0x74, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x16, 0x2e, 0x6d, 0x6c,
|
||||
0x62, 0x63, 0x74, 0x6c, 0x2e, 0x67, 0x65, 0x74, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x50, 0x61, 0x72,
|
||||
0x61, 0x6d, 0x73, 0x1a, 0x16, 0x2e, 0x6d, 0x6c, 0x62, 0x63, 0x74, 0x6c, 0x2e, 0x67, 0x65, 0x74,
|
||||
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x22, 0x00, 0x42, 0x0a, 0x5a,
|
||||
0x08, 0x2e, 0x3b, 0x6d, 0x6c, 0x62, 0x63, 0x74, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
|
||||
0x33,
|
||||
})
|
||||
|
||||
var (
|
||||
file_mlbctl_proto_rawDescOnce sync.Once
|
||||
file_mlbctl_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_mlbctl_proto_rawDescGZIP() []byte {
|
||||
file_mlbctl_proto_rawDescOnce.Do(func() {
|
||||
file_mlbctl_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_mlbctl_proto_rawDesc), len(file_mlbctl_proto_rawDesc)))
|
||||
})
|
||||
return file_mlbctl_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_mlbctl_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_mlbctl_proto_goTypes = []any{
|
||||
(*GetHelloParams)(nil), // 0: mlbctl.getHelloParams
|
||||
(*GetHelloResult)(nil), // 1: mlbctl.getHelloResult
|
||||
}
|
||||
var file_mlbctl_proto_depIdxs = []int32{
|
||||
0, // 0: mlbctl.Control.getHello:input_type -> mlbctl.getHelloParams
|
||||
1, // 1: mlbctl.Control.getHello:output_type -> mlbctl.getHelloResult
|
||||
1, // [1:2] is the sub-list for method output_type
|
||||
0, // [0:1] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_mlbctl_proto_init() }
|
||||
func file_mlbctl_proto_init() {
|
||||
if File_mlbctl_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_mlbctl_proto_rawDesc), len(file_mlbctl_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_mlbctl_proto_goTypes,
|
||||
DependencyIndexes: file_mlbctl_proto_depIdxs,
|
||||
MessageInfos: file_mlbctl_proto_msgTypes,
|
||||
}.Build()
|
||||
File_mlbctl_proto = out.File
|
||||
file_mlbctl_proto_goTypes = nil
|
||||
file_mlbctl_proto_depIdxs = nil
|
||||
}
|
||||
110
pkg/mlbctl/mlbctl_grpc.pb.go
Normal file
110
pkg/mlbctl/mlbctl_grpc.pb.go
Normal file
@@ -0,0 +1,110 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.3.0
|
||||
// - protoc v3.21.12
|
||||
// source: mlbctl.proto
|
||||
|
||||
package mlbctl
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.62.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion8
|
||||
|
||||
const (
|
||||
Control_GetHello_FullMethodName = "/mlbctl.Control/getHello"
|
||||
)
|
||||
|
||||
// ControlClient is the client API for Control service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type ControlClient interface {
|
||||
GetHello(ctx context.Context, in *GetHelloParams, opts ...grpc.CallOption) (*GetHelloResult, error)
|
||||
}
|
||||
|
||||
type controlClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewControlClient(cc grpc.ClientConnInterface) ControlClient {
|
||||
return &controlClient{cc}
|
||||
}
|
||||
|
||||
func (c *controlClient) GetHello(ctx context.Context, in *GetHelloParams, opts ...grpc.CallOption) (*GetHelloResult, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetHelloResult)
|
||||
err := c.cc.Invoke(ctx, Control_GetHello_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ControlServer is the server API for Control service.
|
||||
// All implementations must embed UnimplementedControlServer
|
||||
// for forward compatibility
|
||||
type ControlServer interface {
|
||||
GetHello(context.Context, *GetHelloParams) (*GetHelloResult, error)
|
||||
mustEmbedUnimplementedControlServer()
|
||||
}
|
||||
|
||||
// UnimplementedControlServer must be embedded to have forward compatible implementations.
|
||||
type UnimplementedControlServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedControlServer) GetHello(context.Context, *GetHelloParams) (*GetHelloResult, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetHello not implemented")
|
||||
}
|
||||
func (UnimplementedControlServer) mustEmbedUnimplementedControlServer() {}
|
||||
|
||||
// UnsafeControlServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to ControlServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeControlServer interface {
|
||||
mustEmbedUnimplementedControlServer()
|
||||
}
|
||||
|
||||
func RegisterControlServer(s grpc.ServiceRegistrar, srv ControlServer) {
|
||||
s.RegisterService(&Control_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _Control_GetHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetHelloParams)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ControlServer).GetHello(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: Control_GetHello_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ControlServer).GetHello(ctx, req.(*GetHelloParams))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// Control_ServiceDesc is the grpc.ServiceDesc for Control service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var Control_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "mlbctl.Control",
|
||||
HandlerType: (*ControlServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "getHello",
|
||||
Handler: _Control_GetHello_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "mlbctl.proto",
|
||||
}
|
||||
116
pkg/passwd/passwd.go
Normal file
116
pkg/passwd/passwd.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package passwd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var rnd *rand.Rand
|
||||
|
||||
const (
|
||||
sha256Prefix = "sha256pwd"
|
||||
sha512Prefix = "sha512pwd"
|
||||
saltSize = 12
|
||||
)
|
||||
|
||||
func init() {
|
||||
src := rand.NewSource(time.Now().UnixNano())
|
||||
rnd = rand.New(src)
|
||||
}
|
||||
|
||||
func MakeSHA256Hash(passwd []byte) string {
|
||||
var res string
|
||||
salt := hex.EncodeToString(randomBytes(saltSize))
|
||||
passwdString := hex.EncodeToString(passwd)
|
||||
passwdString = fmt.Sprintf("%s%s", passwdString, salt)
|
||||
|
||||
hasher := sha256.New()
|
||||
hasher.Write([]byte(passwdString))
|
||||
checksum := hex.EncodeToString(hasher.Sum(nil))
|
||||
|
||||
res = fmt.Sprintf("%s:%s:%s", sha256Prefix, salt, checksum)
|
||||
return res
|
||||
}
|
||||
|
||||
func MakeSHA512Hash(passwd []byte) string {
|
||||
var res string
|
||||
salt := hex.EncodeToString(randomBytes(saltSize))
|
||||
passwdString := hex.EncodeToString(passwd)
|
||||
passwdString = fmt.Sprintf("%s%s", passwdString, salt)
|
||||
|
||||
hasher := sha512.New()
|
||||
hasher.Write([]byte(passwdString))
|
||||
checksum := hex.EncodeToString(hasher.Sum(nil))
|
||||
|
||||
res = fmt.Sprintf("%s:%s:%s", sha512Prefix, salt, checksum)
|
||||
return res
|
||||
}
|
||||
|
||||
func PasswordMatchCompat(passwd []byte, hash string) bool {
|
||||
if strings.HasPrefix(hash, sha256Prefix) || strings.HasPrefix(hash, sha512Prefix) {
|
||||
return PasswordMatch(passwd, hash)
|
||||
}
|
||||
if bytes.Equal(passwd, []byte(hash)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
}
|
||||
|
||||
func PasswordMatch(passwd []byte, hash string) bool {
|
||||
hashComponents := strings.Split(hash, ":")
|
||||
if len(hashComponents) != 3 {
|
||||
return false
|
||||
}
|
||||
method := hashComponents[0]
|
||||
salt := hashComponents[1]
|
||||
controlChecksum := hashComponents[2]
|
||||
|
||||
switch method {
|
||||
case sha256Prefix:
|
||||
passwdString := hex.EncodeToString(passwd)
|
||||
passwdString = fmt.Sprintf("%s%s", passwdString, salt)
|
||||
hasher := sha256.New()
|
||||
hasher.Write([]byte(passwdString))
|
||||
checksum := hex.EncodeToString(hasher.Sum(nil))
|
||||
if checksum != controlChecksum {
|
||||
return false
|
||||
}
|
||||
case sha512Prefix:
|
||||
passwdString := hex.EncodeToString(passwd)
|
||||
passwdString = fmt.Sprintf("%s%s", passwdString, salt)
|
||||
hasher := sha512.New()
|
||||
hasher.Write([]byte(passwdString))
|
||||
checksum := hex.EncodeToString(hasher.Sum(nil))
|
||||
if checksum != controlChecksum {
|
||||
return false
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
const letters = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
arr := make([]byte, n)
|
||||
lettersArrayLen := len(letters)
|
||||
for i := range arr {
|
||||
arr[i] = letters[rnd.Intn(lettersArrayLen)]
|
||||
}
|
||||
return string(arr)
|
||||
}
|
||||
|
||||
func randomBytes(n int) []byte {
|
||||
arr := make([]byte, n)
|
||||
for i := range arr {
|
||||
arr[i] = byte(rnd.Intn(256) & 0xFF)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
51
pkg/passwd/passwd_test.go
Normal file
51
pkg/passwd/passwd_test.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package passwd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPasswd256(t *testing.T) {
|
||||
password := []byte("lbmanager")
|
||||
wrongPasswd := []byte("qwerty")
|
||||
|
||||
hash := MakeSHA256Hash(password)
|
||||
fmt.Printf("%s\n", hash)
|
||||
{
|
||||
match := PasswordMatchCompat(password, hash)
|
||||
require.Equal(t, true, match)
|
||||
}
|
||||
{
|
||||
match := PasswordMatchCompat(wrongPasswd, hash)
|
||||
require.NotEqual(t, true, match)
|
||||
}
|
||||
}
|
||||
|
||||
func xxxTestPasswd256X(t *testing.T) {
|
||||
password := []byte("1234567890")
|
||||
|
||||
hash := "sha256pwd:1362271d756aa59e78a53c2ea65433b0:13cfe8d667b92ca3b050bb631ed76f7af218f8f23075ee0cabddb71103b39d93"
|
||||
fmt.Printf("%s\n", hash)
|
||||
{
|
||||
match := PasswordMatch(password, hash)
|
||||
require.Equal(t, true, match)
|
||||
}
|
||||
}
|
||||
|
||||
func xxxTestPasswd512(t *testing.T) {
|
||||
password := []byte("123456781")
|
||||
wrongPasswd := []byte("qwerty")
|
||||
|
||||
hash := MakeSHA512Hash(password)
|
||||
fmt.Printf("%s\n", hash)
|
||||
{
|
||||
match := PasswordMatchCompat(password, hash)
|
||||
require.Equal(t, true, match)
|
||||
}
|
||||
{
|
||||
match := PasswordMatchCompat(wrongPasswd, hash)
|
||||
require.NotEqual(t, true, match)
|
||||
}
|
||||
}
|
||||
133
pkg/x509crt/x509cert.go
Normal file
133
pkg/x509crt/x509cert.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package x509crt
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"time"
|
||||
)
|
||||
|
||||
func CreateX509SelfSignedCert(subject string, hostnames ...string) ([]byte, []byte, error) {
|
||||
var err error
|
||||
|
||||
certPem := make([]byte, 0)
|
||||
keyPem := make([]byte, 0)
|
||||
|
||||
now := time.Now()
|
||||
|
||||
const yearsAfter int = 10
|
||||
const keySize int = 2048
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, keySize)
|
||||
if err != nil {
|
||||
err := fmt.Errorf("Can't create a private key: %v", err)
|
||||
return certPem, keyPem, err
|
||||
|
||||
}
|
||||
keyPemBlock := pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: x509.MarshalPKCS1PrivateKey(key),
|
||||
}
|
||||
keyPem = pem.EncodeToMemory(&keyPemBlock)
|
||||
|
||||
certSubject := pkix.Name{
|
||||
CommonName: subject,
|
||||
}
|
||||
certIssuer := certSubject
|
||||
|
||||
dnsNames := make([]string, 0)
|
||||
dnsNames = append(dnsNames, subject)
|
||||
dnsNames = append(dnsNames, hostnames...)
|
||||
tml := x509.Certificate{
|
||||
SerialNumber: big.NewInt(now.Unix()),
|
||||
NotBefore: now,
|
||||
NotAfter: now.AddDate(yearsAfter, 0, 0),
|
||||
Subject: certSubject,
|
||||
Issuer: certIssuer,
|
||||
DNSNames: dnsNames,
|
||||
BasicConstraintsValid: true,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
|
||||
KeyUsage: x509.KeyUsageDigitalSignature |
|
||||
x509.KeyUsageContentCommitment |
|
||||
x509.KeyUsageKeyEncipherment |
|
||||
x509.KeyUsageDataEncipherment,
|
||||
}
|
||||
certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return certPem, keyPem, fmt.Errorf("Can't create a certificate: %v", err)
|
||||
|
||||
}
|
||||
certPemBlock := pem.Block{
|
||||
Type: "CERTIFICATE",
|
||||
Bytes: certBytes,
|
||||
}
|
||||
certPem = pem.EncodeToMemory(&certPemBlock)
|
||||
if err != nil {
|
||||
return certPem, keyPem, err
|
||||
}
|
||||
return certPem, keyPem, err
|
||||
}
|
||||
|
||||
func CreateX509CACert(commonName string) ([]byte, []byte, error) {
|
||||
var err error
|
||||
certPem := make([]byte, 0)
|
||||
keyPem := make([]byte, 0)
|
||||
|
||||
now := time.Now()
|
||||
|
||||
const yearsAfter int = 10
|
||||
const keySize int = 2048
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, keySize)
|
||||
if err != nil {
|
||||
err := fmt.Errorf("Can't create a private key: %v", err)
|
||||
return certPem, keyPem, err
|
||||
|
||||
}
|
||||
keyPemBlock := pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: x509.MarshalPKCS1PrivateKey(key),
|
||||
}
|
||||
keyPem = pem.EncodeToMemory(&keyPemBlock)
|
||||
|
||||
certSubject := pkix.Name{
|
||||
CommonName: commonName,
|
||||
}
|
||||
certIssuer := certSubject
|
||||
|
||||
tml := x509.Certificate{
|
||||
SerialNumber: big.NewInt(now.Unix()),
|
||||
NotBefore: now,
|
||||
NotAfter: now.AddDate(yearsAfter, 0, 0),
|
||||
Subject: certSubject,
|
||||
Issuer: certIssuer,
|
||||
IsCA: true,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{
|
||||
x509.ExtKeyUsageClientAuth,
|
||||
x509.ExtKeyUsageServerAuth},
|
||||
KeyUsage: x509.KeyUsageDigitalSignature |
|
||||
x509.KeyUsageCertSign |
|
||||
x509.KeyUsageKeyEncipherment |
|
||||
x509.KeyUsageCRLSign,
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return certPem, keyPem, fmt.Errorf("Can't create a certificate: %v", err)
|
||||
|
||||
}
|
||||
certPemBlock := pem.Block{
|
||||
Type: "CERTIFICATE",
|
||||
Bytes: certBytes,
|
||||
}
|
||||
certPem = pem.EncodeToMemory(&certPemBlock)
|
||||
|
||||
if err != nil {
|
||||
return certPem, keyPem, err
|
||||
}
|
||||
return certPem, keyPem, err
|
||||
}
|
||||
31
pkg/x509crt/x509cert_test.go
Normal file
31
pkg/x509crt/x509cert_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
//go:build originate_test
|
||||
|
||||
package x509crt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCert(t *testing.T) {
|
||||
|
||||
{
|
||||
//caCert, caKey, err := CreateX509SelfSignedCert("test1")
|
||||
//require.NoError(t, err)
|
||||
//fmt.Println(string(caCert))
|
||||
//fmt.Println(string(caKey))
|
||||
}
|
||||
{
|
||||
caCert, caKey, err := CreateX509CACert("test1")
|
||||
require.NoError(t, err)
|
||||
fmt.Println(string(caCert))
|
||||
fmt.Println(string(caKey))
|
||||
|
||||
// caCert, caKey, err = CreateX509Cert("test1", caKey)
|
||||
// require.NoError(t, err)
|
||||
// fmt.Println(string(caCert))
|
||||
// fmt.Println(string(caKey))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user