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 ¶
- Variables
- func AbsWithBranch(n int) int
- func AbsWithTwosComplement(n int64) int64
- func Atoi(num string) int
- func Atoi64(num string) int64
- func ByteSliceEqual(a []byte, b []byte) bool
- func BytesToPrivateKey(data []byte) (*rsa.PrivateKey, error)
- func BytesToPublicKey(data []byte) (*rsa.PublicKey, error)
- func CloneByteSlice(a []byte, low int, high int) []byte
- func CloneIntSlice(src []int) ([]int, int)
- func Close(c io.Closer)
- func ConvErrArrToJSON(errArr []error) string
- func ConvErrArrToStringArr(errArr []error) []string
- func ConvSliceToInterface(slice interface{}) []interface{}
- func ConvStrToTime(str string) (time.Time, error)
- func CopyIntSlice(dst []int, src []int) int
- func CreateHash(data string) []byte
- func DaysAgo(t time.Time) int
- func DecodeJSONStreamMap(r *http.Request) (map[string]interface{}, error)
- func DecodeJSONStreamStruct(r *http.Request, v interface{}) error
- func DecryptAES(data []byte, passphrase string) ([]byte, error)
- func DecryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error)
- func DeferClose(e *error, c io.Closer)
- func EchoColor(msg string, color string) string
- func EncryptAES(data []byte, passphrase string) ([]byte, error)
- func EncryptWithPublicKey(msg []byte, pub *rsa.PublicKey) ([]byte, error)
- func ExecCommand(cmdArgs []string, timeout int) (string, int, error)
- func FormValueArr(r *http.Request) map[string]string
- func GenerateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error)
- func GenerateRandomBytes(n int) ([]byte, error)
- func GenerateRandomString(s int) (string, error)
- func GetEnv(key, fallback string) string
- func GetSliceHeader(buf []string) *reflect.SliceHeader
- func HMACHash(message string, secret string) string
- func HashPassword(plaintextPassword string) ([]byte, error)
- func InArrayInt(v int, vArr []int) bool
- func InArrayStr(v string, vArr []string) bool
- func InArrayV1(val interface{}, array interface{}) (exists bool, index int)
- func InArrayV2(v interface{}, in interface{}) (ok bool, i int)
- func IntSliceEqual(a []int, b []int) bool
- func IntToDigitArr(num int) []int
- func JSONDeepEqual(s1 string, s2 string) (bool, error)
- func Now() string
- func NumOfDigitsDivideAndConquer(num int) int
- func NumOfDigitsDivideAndConquerHardCoded(num int) int
- func NumOfDigitsLog10(num int) int
- func NumOfDigitsRepeatedDivide(num int) int
- func NumOfDigitsString(num int) int
- func Placeholder(num int) string
- func Pow(a int, b int) int
- func PowOfTenArr() []int
- func PrintErrJSON(rowArr []error)
- func PrintJSON(rowArr []interface{})
- func PrintStructJSON(s interface{})
- func PrivateKeyToBytes(priv *rsa.PrivateKey) []byte
- func PublicKeyToBytes(pub *rsa.PublicKey) ([]byte, error)
- func RandStringBytes(n int) string
- func RandStringRunes(n int) string
- func RandomDate(numOfYear int) string
- func RandomNumInSlice(slice []int) int
- func RandomNumber(min, max int) int
- func ReadFile(fileName string) ([]byte, error)
- func ReadInput() (string, error)
- func ReadWebContent(url string) ([]byte, error)
- func SignSignature(privateKey *rsa.PrivateKey, data []byte) ([]byte, error)
- func SliceFill(num int, str string) []string
- func StrToUint32(num string) uint32
- func StructFieldNameArr(s interface{}) []string
- func StrutToSliceOfFieldAddress(theStruct interface{}) []interface{}
- func Uint32ToStr(num uint32) string
- func ValidatePassword(hashed string, plaintextPassword string) error
- func VerifySignature(publicKey *rsa.PublicKey, data []byte, sig []byte) error
- func WaitForServer(url string) error
- func WriteFile(fileName string, data []byte) error
Constants ¶
This section is empty.
Variables ¶
var FGColor = struct { White, Red, Green, Yellow string }{ White: "1;37", Red: "0;31", Green: "0;32", Yellow: "1;33", }
FGColor ...
Functions ¶
func AbsWithBranch ¶
AbsWithBranch returns the absolute value of x. NOTE: -9223372036854775808 could not be convert.
func AbsWithTwosComplement ¶
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 ByteSliceEqual ¶
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 ¶
BytesToPublicKey bytes to public key
func CloneByteSlice ¶
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 ConvErrArrToStringArr ¶
ConvErrArrToStringArr ...
func ConvSliceToInterface ¶
func ConvSliceToInterface(slice interface{}) []interface{}
ConvSliceToInterface ...
func DecodeJSONStreamMap ¶
DecodeJSONStreamMap ...
func DecodeJSONStreamStruct ¶
DecodeJSONStreamStruct ...
func DecryptWithPrivateKey ¶
func DecryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error)
DecryptWithPrivateKey decrypts data with private key
func DeferClose ¶
DeferClose ... defer DeferClose(&err, rsp.Body.Close) Note: https://github.com/carlmjohnson/json-tidy/blob/master/json-tidy.go#L91:L96
func EncryptWithPublicKey ¶
EncryptWithPublicKey encrypts data with public key
func ExecCommand ¶
ExecCommand ...
func GenerateKeyPair ¶
GenerateKeyPair generates a new key pair
func GenerateRandomBytes ¶
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 ¶
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 IntSliceEqual ¶
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 IntToDigitArr ¶
IntToDigitArr separates the digits of an integer into a slice Reference: https://stackoverflow.com/questions/1613317/fastest-way-to-separate-the-digits-of-an-int-into-an-array-in-net https://stackoverflow.com/questions/4261589/how-do-i-split-an-int-into-its-digits
func NumOfDigitsDivideAndConquer ¶
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 ¶
NumOfDigitsDivideAndConquerHardCoded (Divide and conquer hard-coded approach) ...
func NumOfDigitsLog10 ¶
NumOfDigitsLog10 (log10 approach) ... NOTE: this function is not 100% correct
func NumOfDigitsRepeatedDivide ¶
NumOfDigitsRepeatedDivide (repeated divide approach) ...
func NumOfDigitsString ¶
NumOfDigitsString (string approach) ...
func Placeholder ¶
Placeholder generates the placeholders for SQL query.
func Pow ¶
Pow computes a**b using binary powering algorithm See Donald Knuth, The Art of Computer Programming, Volume 2, Section 4.6.3
func PrivateKeyToBytes ¶
func PrivateKeyToBytes(priv *rsa.PrivateKey) []byte
PrivateKeyToBytes private key to bytes
func PublicKeyToBytes ¶
PublicKeyToBytes public key to bytes
func RandomNumber ¶
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 ReadWebContent ¶
func SignSignature ¶
func SignSignature(privateKey *rsa.PrivateKey, data []byte) ([]byte, error)
SignSignature signs the data with a private key
func StrToUint32 ¶
StrToUint32 converts uint32 string to uint32 integer
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 ¶
Uint32ToStr converts uint32 integer to string
func ValidatePassword ¶
ValidatePassword ...
func VerifySignature ¶
VerifySignature verifies the data with a public key
func WaitForServer ¶
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.
Types ¶
This section is empty.