util

package module
v0.0.0-...-b944ef0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 23, 2021 License: MIT Imports: 31 Imported by: 4

README

util

Documentation

Overview

Package util ...

PKCS#1 and PKCS#8 format for RSA private key

PKCS1, available in several versions as rfcs 2313 2437 3447 and 8017, is primarily about using the RSA algorithm for cryptography including encrypting decrypting signing and verifying. But since crypto is often used between systems or at least programs it is convenient to have a defined, interoperable format for keys, and PKCS1 defines fairly minimal formats for RSA public and private keys in appendix A.1. As Luke implied this uses ASN.1 conventionally encoded as DER, which is a standard for interoperably encoding data of almost any kind.

PKCS8 available as rfc5208 on the other hand is a standard for handling private keys for all algorithms, not just RSA. It also uses ASN.1 DER, and starts by simply combining an AlgorithmIdentifier, an ASN.1 structure (first) defined by X.509 which not very surprisingly identifies an algorithm, with an OCTET STRING which contains a representation of the key in a fashion depending on the algorithm. For algorithm RSA, identified by an AlgorithmIdentifier containing an OID which means rsaEncryption, the OCTET STRING contains the PKCS1 private key encoding. PKCS8 also allows arbitrary 'attributes' to be added, but this is rarely used. (E.g. Unable to convert .jks to .pkcs12: excess private key)

PKCS8 also provides an option to encrypt the private key, using password-based encryption (in practice though not explicitly required). This is common, especially when PKCS8 is used as the privatekey portion of PKCS12/PFX, though not universal.

Since most systems today need to support multiple algorithms, and wish to be able to adapt to new algorithms as they are developed, PKCS8 is preferred for privatekeys, and a similar any-algorithm scheme defined by X.509 for publickeys. Although PKCS12/PFX is often preferred to both.

Neither of these has anything to do with certificates or other PKI objects like CSRs, CRLs, OCSP, SCTs, etc. Those are defined by other standards, including some other members of the PKCS series -- although they may use the keys defined by these standards.

PEM format as Luke said is a way of formatting, or (super)encoding, (almost any) binary/DER data in a way that is more convenient. It derives from a 1990s attempt at secure email named Privacy-Enhanced Mail hence PEM. In those days email systems often could transmit, or at least reliably transmit, only printable text with a limited character set, and often only limited line length, so PEM encoded binary data as base64 with line length 64. The PEM scheme itself was not very successful and has been superseded by others like PGP and S/MIME, but the format it defined is still used. Nowadays email systems often can transmit binary data, but as Luke said copy-and-paste often can only handle displayed characters so PEM is still useful, and in addition easier for humans to recognize.

To be more exact, PEM encodes some data, such as but not limited to a PKCS1 or PKCS8 key or a certificate, CSR, etc, as:

- a line consisting of 5 hyphens, the word BEGIN, one or a few (space-separated) words defining the type of data, and 5 hyphens - an optional (and rare) rfc822-style header, terminated by an empty line - base64 of the data, broken into lines of 64 characters (except the last); some programs instead use the (slightly newer) MIME limit of 76 characters - a line like the BEGIN line but with END instead

Some readers check/enforce the line length and END line and some don't, so if you get those wrong you may create files that sometimes work and sometimes don't, which is annoying to debug.

Reference: https://gist.github.com/miguelmota/3ea9286bd1d3c2a985b67cac4ba2130a https://stackoverflow.com/questions/48958304/pkcs1-and-pkcs8-format-for-rsa-private-key https://www.thepolyglotdeveloper.com/2018/02/encrypt-decrypt-data-golang-application-crypto-packages/ https://tutorialedge.net/golang/go-encrypt-decrypt-aes-tutorial/ https://github.com/gtank/cryptopasta

Package util ...

Index

Constants

This section is empty.

Variables

View Source
var FGColor = struct {
	White, Red, Green, Yellow string
}{
	White:  "1;37",
	Red:    "0;31",
	Green:  "0;32",
	Yellow: "1;33",
}

FGColor ...

Functions

func AbsWithBranch

func AbsWithBranch(n int) int

AbsWithBranch returns the absolute value of x. NOTE: -9223372036854775808 could not be convert.

func AbsWithTwosComplement

func AbsWithTwosComplement(n int64) int64

AbsWithTwosComplement returns the absolute value of x. NOTE: -9223372036854775808 could not be convert. Reference: http://cavaliercoder.com/blog/optimized-abs-for-int64-in-go.html

func Atoi

func Atoi(num string) int

Atoi ...

func Atoi64

func Atoi64(num string) int64

Atoi64 ...

func ByteSliceEqual

func ByteSliceEqual(a []byte, b []byte) bool

ByteSliceEqual tells whether a and b contain the same elements. A nil argument is equivalent to an empty slice. NOTE: https://yourbasic.org/golang/compare-slices/

func BytesToPrivateKey

func BytesToPrivateKey(data []byte) (*rsa.PrivateKey, error)

BytesToPrivateKey bytes to private key

func BytesToPublicKey

func BytesToPublicKey(data []byte) (*rsa.PublicKey, error)

BytesToPublicKey bytes to public key

func CloneByteSlice

func CloneByteSlice(a []byte, low int, high int) []byte

CloneByteSlice ... (Note: The way introduced in this article is not the best solution universally. For some scenarios, the target slice is expected to be nil even if the source slice is a non-nil blank one, to avoid sharing underlying elements.) (Note 2: There is an imperfection in the perfect clone implementation: the final capacity might be not the same as the original one.) https://github.com/go101/go101/wiki/How-to-perfectly-clone-a-slice%3F

func CloneIntSlice

func CloneIntSlice(src []int) ([]int, int)

CloneIntSlice ...

func Close

func Close(c io.Closer)

Close is used for defer statement. Example: defer Close(VarResource)

func ConvErrArrToJSON

func ConvErrArrToJSON(errArr []error) string

ConvErrArrToJSON ...

func ConvErrArrToStringArr

func ConvErrArrToStringArr(errArr []error) []string

ConvErrArrToStringArr ...

func ConvSliceToInterface

func ConvSliceToInterface(slice interface{}) []interface{}

ConvSliceToInterface ...

func ConvStrToTime

func ConvStrToTime(str string) (time.Time, error)

func CopyIntSlice

func CopyIntSlice(dst []int, src []int) int

CopyIntSlice ...

func CreateHash

func CreateHash(data string) []byte

CreateHash ...

func DaysAgo

func DaysAgo(t time.Time) int

func DecodeJSONStreamMap

func DecodeJSONStreamMap(r *http.Request) (map[string]interface{}, error)

DecodeJSONStreamMap ...

func DecodeJSONStreamStruct

func DecodeJSONStreamStruct(r *http.Request, v interface{}) error

DecodeJSONStreamStruct ...

func DecryptAES

func DecryptAES(data []byte, passphrase string) ([]byte, error)

DecryptAES ...

func DecryptWithPrivateKey

func DecryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error)

DecryptWithPrivateKey decrypts data with private key

func DeferClose

func DeferClose(e *error, c io.Closer)

DeferClose ... defer DeferClose(&err, rsp.Body.Close) Note: https://github.com/carlmjohnson/json-tidy/blob/master/json-tidy.go#L91:L96

func EchoColor

func EchoColor(msg string, color string) string

EchoColor ...

func EncryptAES

func EncryptAES(data []byte, passphrase string) ([]byte, error)

EncryptAES ...

func EncryptWithPublicKey

func EncryptWithPublicKey(msg []byte, pub *rsa.PublicKey) ([]byte, error)

EncryptWithPublicKey encrypts data with public key

func ExecCommand

func ExecCommand(cmdArgs []string, timeout int) (string, int, error)

ExecCommand ...

func FormValueArr

func FormValueArr(r *http.Request) map[string]string

FormValueArr ...

func GenerateKeyPair

func GenerateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error)

GenerateKeyPair generates a new key pair

func GenerateRandomBytes

func GenerateRandomBytes(n int) ([]byte, error)

GenerateRandomBytes returns securely generated random bytes. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue. Reference: https://elithrar.github.io/article/generating-secure-random-numbers-crypto-rand/

func GenerateRandomString

func GenerateRandomString(s int) (string, error)

GenerateRandomString returns a URL-safe, base64 encoded securely generated random string. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func GetEnv

func GetEnv(key, fallback string) string

GetEnv ...

func GetSliceHeader

func GetSliceHeader(buf []string) *reflect.SliceHeader

GetSliceHeader ...

func HMACHash

func HMACHash(message string, secret string) string

HMACHash hashes data using a secret key

func HashPassword

func HashPassword(plaintextPassword string) ([]byte, error)

HashPassword ...

func InArrayInt

func InArrayInt(v int, vArr []int) bool

InArrayInt ...

func InArrayStr

func InArrayStr(v string, vArr []string) bool

InArrayStr ...

func InArrayV1

func InArrayV1(val interface{}, array interface{}) (exists bool, index int)

InArrayV1 ...

func InArrayV2

func InArrayV2(v interface{}, in interface{}) (ok bool, i int)

InArrayV2 ...

func IntSliceEqual

func IntSliceEqual(a []int, b []int) bool

IntSliceEqual tells whether a and b contain the same elements. A nil argument is equivalent to an empty slice. NOTE: https://yourbasic.org/golang/compare-slices/

func JSONDeepEqual

func JSONDeepEqual(s1 string, s2 string) (bool, error)

JSONDeepEqual ...

func Now

func Now() string

func NumOfDigitsDivideAndConquer

func NumOfDigitsDivideAndConquer(num int) int

NumOfDigitsDivideAndConquer (Divide and conquer approach) ... Here are some ways of determining the number of digits in an integer: - string method - log10 method - repeated divide method - divide-and-conquer method Reference: https://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int/1308407#1308407

func NumOfDigitsDivideAndConquerHardCoded

func NumOfDigitsDivideAndConquerHardCoded(num int) int

NumOfDigitsDivideAndConquerHardCoded (Divide and conquer hard-coded approach) ...

func NumOfDigitsLog10

func NumOfDigitsLog10(num int) int

NumOfDigitsLog10 (log10 approach) ... NOTE: this function is not 100% correct

func NumOfDigitsRepeatedDivide

func NumOfDigitsRepeatedDivide(num int) int

NumOfDigitsRepeatedDivide (repeated divide approach) ...

func NumOfDigitsString

func NumOfDigitsString(num int) int

NumOfDigitsString (string approach) ...

func Placeholder

func Placeholder(num int) string

Placeholder generates the placeholders for SQL query.

func Pow

func Pow(a int, b int) int

Pow computes a**b using binary powering algorithm See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3

func PowOfTenArr

func PowOfTenArr() []int

PowOfTenArr ...

func PrintErrJSON

func PrintErrJSON(rowArr []error)

PrintErrJSON ...

func PrintJSON

func PrintJSON(rowArr []interface{})

PrintJSON ...

func PrintStructJSON

func PrintStructJSON(s interface{})

PrintStructJSON ...

func PrivateKeyToBytes

func PrivateKeyToBytes(priv *rsa.PrivateKey) []byte

PrivateKeyToBytes private key to bytes

func PublicKeyToBytes

func PublicKeyToBytes(pub *rsa.PublicKey) ([]byte, error)

PublicKeyToBytes public key to bytes

func RandStringBytes

func RandStringBytes(n int) string

RandStringBytes ...

func RandStringRunes

func RandStringRunes(n int) string

RandStringRunes ...

func RandomDate

func RandomDate(numOfYear int) string

RandomDate ...

func RandomNumInSlice

func RandomNumInSlice(slice []int) int

RandomNumInSlice ...

func RandomNumber

func RandomNumber(min, max int) int

RandomNumber generates a random number in a given range. This code is vulnerable to a time attack. Given knowledge of the seed, the output is deterministic. If you are on linux, you could poll "/dev/random" or "/dev/urandom" and have that be your seed. Or better yet, use crypto/rand. Reference: http://golangcookbook.blogspot.ca/2012/11/generate-random-number-in-given-range.html

func ReadFile

func ReadFile(fileName string) ([]byte, error)

func ReadInput

func ReadInput() (string, error)

func ReadWebContent

func ReadWebContent(url string) ([]byte, error)

func SignSignature

func SignSignature(privateKey *rsa.PrivateKey, data []byte) ([]byte, error)

SignSignature signs the data with a private key

func SliceFill

func SliceFill(num int, str string) []string

SliceFill fills a slice with values.

func StrToUint32

func StrToUint32(num string) uint32

StrToUint32 converts uint32 string to uint32 integer

func StructFieldNameArr

func StructFieldNameArr(s interface{}) []string

StructFieldNameArr ...

func StrutToSliceOfFieldAddress

func StrutToSliceOfFieldAddress(theStruct interface{}) []interface{}

StrutToSliceOfFieldAddress can be used for rows.Scan() for setting the value for database fields from SQL query.

func Uint32ToStr

func Uint32ToStr(num uint32) string

Uint32ToStr converts uint32 integer to string

func ValidatePassword

func ValidatePassword(hashed string, plaintextPassword string) error

ValidatePassword ...

func VerifySignature

func VerifySignature(publicKey *rsa.PublicKey, data []byte, sig []byte) error

VerifySignature verifies the data with a public key

func WaitForServer

func WaitForServer(url string) error

WaitForServer attempts to contact the server of a URL. It tries for one minute using exponential backoff. It reports an error if all attempts fail.

func WriteFile

func WriteFile(fileName string, data []byte) error

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL