Documentation ¶
Overview ¶
Copyright (c) 2018-Now Dunyu All Rights Reserved.
Author : https://www.wengold.net Email : support@wengold.net
Prismy.No | Date | Modified by. | Description ------------------------------------------------------------------- 00001 2019/05/22 yangping New version -------------------------------------------------------------------
Index ¶
- Constants
- func AESDecrypt(secretkey []byte, ciphertextb64 string) (string, error)
- func AESEncrypt(secretkey, original []byte) (string, error)
- func Base64ToByte(ciphertext string) ([]byte, error)
- func ByteToBase64(original []byte) string
- func DecClaims(keyword string, count ...int) ([]string, error)
- func DecJwtKeyword(keyword string) (string, string, string)deprecated
- func DecodeBase64(ciphertext string) (string, error)
- func EccDigitalSigns(sign []byte) (*big.Int, *big.Int)
- func EccKeysString(prikey *ecdsa.PrivateKey) (string, string, error)
- func EccPriKey(pripem string) (*ecdsa.PrivateKey, error)
- func EccPriString(prikey *ecdsa.PrivateKey) (string, error)
- func EccPubKey(pubkey string) (*ecdsa.PublicKey, error)
- func EccPubString(pubkey *ecdsa.PublicKey) (string, error)
- func EccSign(plaintext string, prikey *ecdsa.PrivateKey) (string, error)
- func EccVerify(plaintext, signb64 string, pubkey *ecdsa.PublicKey) (bool, error)
- func EncClaims(uuid string, params ...string) string
- func EncJwtKeyword(uuid, pwd string, subject string) stringdeprecated
- func EncodeB64MD5(original string) string
- func EncodeBase64(original string) string
- func EncodeMD5(original string) string
- func EncodeMD5B64(original string) string
- func EncodeMD5Check(original string) (string, error)
- func GCMDecrypt(secretkey []byte, ciphertextb64, noncestr string, additional ...[]byte) (string, error)
- func GCMEncrypt(secretkey, original []byte, additional ...[]byte) (string, string, error)
- func GenAESKey() string
- func GenCode() string
- func GenCodeFrom(src int64) string
- func GenEccKeys(sign ...string) (string, string, error)
- func GenEccPriKey(sign ...string) (*ecdsa.PrivateKey, error)
- func GenHash(src, salt string, buflen ...int) (string, error)
- func GenJwtToken(keyword, salt string, dur time.Duration) (string, error)
- func GenLoginToken(acc, pwd string) string
- func GenLowCode() string
- func GenLowNum() string
- func GenNano() string
- func GenNonce() string
- func GenOAuthCode(length int, randomType string) (string, error)
- func GenRSAKeys(bits int) (string, string, error)
- func GenRandCode(seednum ...int64) string
- func GenRandCodeFrom(src int64) string
- func GenRandUUID(buflen ...int) string
- func GenSalt(buflen ...int) (string, error)
- func GenToken(original string) string
- func GenUUID() int64
- func GenUUIDString() string
- func GenUpCode() string
- func GenUpNum() string
- func HashByteThenBase64(data []byte) string
- func HashMD5(original []byte) []byte
- func HashMD5Check(original []byte) ([]byte, error)
- func HashSHA256(original []byte) []byte
- func HashSHA256Hex(original []byte) string
- func HashSHA256String(original string) []byte
- func HashThenBase64(data string) string
- func LoadRSAKey(filepath string, buffbits ...int) ([]byte, error)
- func MD5Lower(original string) string
- func MD5Upper(original string) string
- func RSA2Sign(prikey, original []byte) ([]byte, error)
- func RSA2Sign4F(prifile string, original []byte) ([]byte, error)
- func RSA2Sign4FB64(prifile string, original []byte) (string, error)
- func RSA2SignB64(prikey, original []byte) (string, error)
- func RSA2Verify(pubkey, original, signature []byte) error
- func RSA2Verify4F(pubfile string, original, signature []byte) error
- func RSADecrypt(prikey, ciphertext []byte) ([]byte, error)
- func RSADecrypt4F(prifile string, ciphertext []byte) ([]byte, error)
- func RSAEncrypt(pubkey, original []byte) ([]byte, error)
- func RSAEncrypt4F(pubfile string, original []byte) ([]byte, error)
- func RSAEncrypt4FB64(pubfile string, original []byte) (string, error)
- func RSAEncryptB64(pubkey, original []byte) (string, error)
- func RSASign(prikey, original []byte) ([]byte, error)
- func RSASign4F(prifile string, original []byte) ([]byte, error)
- func RSASign4FB64(prifile string, original []byte) (string, error)
- func RSASignB64(prikey, original []byte) (string, error)
- func RSAVerify(pubkey, original, signature []byte) error
- func RSAVerify4F(pubfile string, original, signature []byte) error
- func RSAVerifyASN(pubkey, original, signature []byte) error
- func RSAVerifyASN4F(pubfile string, original, signature []byte) error
- func SignSHA1(securekey string, src string) string
- func SignSHA256(securekey string, src string) string
- func ToMD5Hex(input ...string) string
- func ToMD5Lower(original string) (string, error)
- func ToMD5Upper(original string) (string, error)
- func ViaJwtToken(signedToken, salt string) (string, error)
- func ViaLoginToken(acc, pwd, token string, duration int64) (bool, error)
- type Claims
- type SoleCoder
- type Stringer
Constants ¶
const ( ECC_PEM_PRI_HEADER = "ECDSA PRIVATE KEY" // private key pem file header ECC_PEM_PUB_HEADER = "ECDSA PUBLIC KEY" // public key pem file header )
const AES_UTIL_DESCRIPTION = 0 /* just use for description */
For other languages, you can use the follows example code to encrypt or decrypt AES.
`AES for java (Android)`
----
public String encryptByAES(String secretkey, String original) { try { // use md5 value as the real key byte[] b = secretkey.getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hashed = md.digest(b); // create an 16-byte initialization vector byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; AlgorithmParameterSpec spec = new IvParameterSpec(iv); SecretKeySpec keyspec = new SecretKeySpec(hashed), "AES"); // create cipher and initialize CBC vector Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ecipher.init(Cipher.ENCRYPT_MODE, keyspec, spec); byte[] plaintext = original.getBytes(); byte[] ciphertext = ecipher.doFinal(plaintext, 0, plaintext.length); return Base64.encodeToString(ciphertext, Base64.DEFAULT); } catch (Exception e) { e.printStackTrace(); } return null; } public String decryptByAES(String secretkey, String ciphertextb64) { try { // use md5 value as the real key byte[] b = secretkey.getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hashed = md.digest(b); // create an 16-byte initialization vector byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; AlgorithmParameterSpec spec = new IvParameterSpec(iv); SecretKeySpec keyspec = new SecretKeySpec(hashed), "AES"); // create cipher and initialize CBC vector Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); dcipher.init(Cipher.DECRYPT_MODE, keyspec, spec); byte[] ciphertext = Base64.decode(ciphertextb64, Base64.DEFAULT); byte[] original = dcipher.doFinal(ciphertext, 0, ciphertext.length); return new String(original); } catch (Exception e) { e.printStackTrace(); } return null; }
`AES for node.js`
----
let iv = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f ]; function encrypt_by_aes(secretkey, original) { let md5 = crypto.createHash('md5').update(secretkey).digest('hex'); const ecipher = crypto.createCipheriv( 'aes-128-cbc', new Buffer(md5, 'hex'), new Buffer(iv) ); // ecipher.setAutoPadding(true); var ciphertextb64 = ecipher.update(original, 'utf8', 'base64'); ciphertextb64 += ecipher.final('base64'); console.log('ciphertextb64: ' + ciphertextb64); return ciphertextb64; } function decrypt_by_aes(secretkey, ciphertextb64) { let md5 = crypto.createHash('md5').update(secretkey).digest('hex'); const dcipher = crypto.createDecipheriv( 'aes-128-cbc', new Buffer(md5, 'hex'), new Buffer(iv) ); var original = dcipher.update(ciphertextb64, 'base64', 'utf8'); original += dcipher.final('utf8'); console.log('original: ' + original); return original; }
const RSA_UTIL_DESCRIPTION = 0 /* just use for description */
### 1. How to encrypt and decrypt by RSA
- (1). use secure.GenRSAKeys() to generate RSA keys, and set content bits length.
- (2). use secure.RSAEncrypt() to encrypt original data with given public key.
- (3). use secure.RSADecrypt() to decrypt ciphertext with given private key.
`USAGE`
// Use the pubkey to encrypt and use the prikey to decrypt prikey, pubkey, _ := secure.GenRSAKeys(1024) logger.I("public key:", pubkey, "private key:", prikey) ciphertext, _ := secure.RSAEncrypt([]byte(pubkey), []byte("original-content")) ciphertextBase64 := secure.EncodeBase64(string(ciphertext)) logger.I("ciphertext base64 string:", ciphertextBase64) original, _ := secure.RSADecrypt([]byte(prikey), ciphertext) logger.I("original string:", string(original)) // print 'original-content'
----
### 2. How to digital signature and verify by RSA
- (1). use secure.GenRSAKeys() to generate RSA keys, and set content bits length.
- (2). use secure.RSASign() to make digital signature with given private key.`
- (3). use secure.RSAVerify() to verify data's integrity with given public key and digital signature
`USAGE`
// Use the private key to create digital signature and use pubkey to verify it prikey, pubkey, _ := secure.GenRSAKeys(1024) logger.I("public key:", pubkey, "private key:", prikey) original := []byte("original-content") signature, _ := secure.RSASign([]byte(prikey), original) logger.I("original string:", string(original)) logger.I("signature string:", string(signature)) if err := secure.RSAVerify([]byte(pubkey), original, signature); err != nil { logger.E("Verify failed with err:", err) return } logger.I("Verify success")
Variables ¶
This section is empty.
Functions ¶
func AESDecrypt ¶
Using CBC formated secret key to decrypt ciphertext
@param secretkey Secure key buffer @param ciphertextb64 Ciphertext formated by base64 @return - string Decrypted plaintext string - error Exception message
func AESEncrypt ¶
Using CBC formated secret key to encrypt original data
@param secretkey Secure key buffer @param original Original datas buffer to encrypt @return - string Encrypted ciphertext formated by base64 - error Exception message
----
secretkey := secure.GenAESKey() original := []byte("original-content") ciphertext, _ := secure.AESEncrypt([]byte(secretkey), original) encrypted, _ := secure.AESDecrypt([]byte(secretkey), ciphertext) logger.I("encrypted original string: ", encrypted)
func Base64ToByte ¶
Decode base64 string to byte array
func DecJwtKeyword
deprecated
func EccDigitalSigns ¶
Parse ECC digital signs from signed string, to veriry plaintext.
prikey, _ := GenEccPriKey() plaintext := "This is a plainttext to sign and verfiy!" signb64, _ := EccSign(plaintext, prikey) valid, _ : EccVerify(plaintext, signb64, &prikey.PublicKey) fmt.Println("ECC verify result:", valid)
func EccKeysString ¶
func EccKeysString(prikey *ecdsa.PrivateKey) (string, string, error)
Format ECC private and public keys to pem strings.
func EccPriKey ¶
func EccPriKey(pripem string) (*ecdsa.PrivateKey, error)
Get ECC private key from private pem string.
prikey, _ := GenEccPriKey() pripem, _ := EccPriString(prikey) newkey, _ := EccPriKey(pripem) // prikey == newkey
func EccPriString ¶
func EccPriString(prikey *ecdsa.PrivateKey) (string, error)
Format ECC private key to pem string, it can be save to file directly.
func EccPubKey ¶
Get ECC public key from public pem string.
prikey, _ := GenEccPriKey() pubpem, _ := EccPubString(&prikey.PublicKey) newkey, _ := EccPubKey(pubpem) // prikey.PublicKey == newkey
func EccPubString ¶
Format ECC public key to pem string, it can be save to file directly.
prikey, _ := secure.GenEccPriKey() pubkey := &prikey.PublicKey // get public key pubstr, _ := secure.EccPubString(pubkey) // format public key to pem string
func EccSign ¶
func EccSign(plaintext string, prikey *ecdsa.PrivateKey) (string, error)
Sign the given plaintext by ECC private key, and return the signed code on base64 format.
func EncJwtKeyword
deprecated
func EncodeB64MD5 ¶
Encode string to base64, and then encode by md5
func EncodeMD5B64 ¶
Encode string to md5, and then encode by base64
func EncodeMD5Check ¶
Encode string by md5 and check write buffer errors
func GCMDecrypt ¶
func GCMDecrypt(secretkey []byte, ciphertextb64, noncestr string, additional ...[]byte) (string, error)
Using AES-256-GCM to decrypt ciphertext
@param secretkey Secure key buffer @param ciphertextb64 Ciphertext formated by base64 @param noncestr Nonce string which generated when encrypt @param additional additional datas used by encrypt, it maybe null @return - string Decrypted plaintext string - error Exception message
func GCMEncrypt ¶
Using AES-256-GCM to encrypt the given original text
@param secretkey Secure key buffer @param original Original datas buffer to encrypt @param additional Additional datas @return - string Encrypted ciphertext formated by base64 - string Nonce string - error Exception message
`NOTICE` :
You can use secure.GenAESKey() to generate a AES-256-GSM secret key to as secretkey input param, or use hex.EncodeToString() encode any secret string, but use hex.DecodeString() decode the encode hash key before call this function.
----
// use secure.GenAESKey() generate a secretkey secretkey := secure.GenAESKey() ciphertex, noncestr, err := secure.GCMEncrypt(secretkey, original) ciphertex, noncestr, err := secure.GCMEncrypt(secretkey, original, additional) // use hex.EncodeToString() and hex.DecodeString() hashkey := hex.EncodeToString(secretkey) // do samething with hashkey... secretkey, err := hex.DecodeString(hashkey) ciphertex, noncestr, err := secure.GCMEncrypt(secretkey, original) ciphertex, noncestr, err := secure.GCMEncrypt(secretkey, original, additional)
func GenCodeFrom ¶
Generate a code from given int64 data, e.g. M25eNdE4rF5
func GenEccKeys ¶
Generate ECC private key, and format private and public keys as pem strings, by default it create P256 curve to sign data, or you can create other keys for set sign param as P224, P384, P521.
@see secure.GenEccPriKey()
func GenEccPriKey ¶
func GenEccPriKey(sign ...string) (*ecdsa.PrivateKey, error)
Generate a ECC random private key with curve type one of P224, P256, P384, P521, or use P256 curve as default, then you can get the pair public key from prikey.PublicKey param.
prikey, _ := secure.GenEccPriKey() // same as secure.GenEccPriKey("P256") pubkey := &prikey.PublicKey // get public key
func GenHash ¶
Hash the given source with salt, default length is 64 * 2, you may set buffer length by buflen input param, and return (buflen * 2) length hash string.
func GenJwtToken ¶
Generate a jwt token with keyword and salt string, the token will expired after the given duration
func GenLoginToken ¶
Generate a login token with account and password.
---
account password |- + -| | base64 current nanosecode | | md5 base64 +------- "."---------| | base64 => token
func GenLowCode ¶
func GenLowCode() string
Generate a code formated only lower chars, e.g. mabendecrfdme
func GenLowNum ¶
func GenLowNum() string
Generate a code formated only number and lower chars, e.g. m25ende4rf5m
func GenNano ¶
func GenNano() string
Generate a code just as current nano seconds time, e.g. 1693359476235899600
func GenOAuthCode ¶
Generate a random OAuth code
func GenRSAKeys ¶
Generate RSA private and public keys in PKCS#1, ASN.1 DER format, and limit bits length of key cert.
@param bits Limit bits length of key cert @return - string Private key original string - string Public key original string - error Exception message
func GenRandCode ¶
Generate a code by using current nanosecond and append random suffix, e.g. M25eNdE4rF50987
func GenRandCodeFrom ¶
Generate a code from given int64 data and append random suffix, e.g. M25eNdE4rF50987
func GenRandUUID ¶
Generate a random number uuid with specified digits
func GenSalt ¶
Generates a random salt, default length is 64 * 2, you may set buffer length by buflen input param, and return (buflen * 2) length salt string.
func GenUpCode ¶
func GenUpCode() string
Generate a code formated only upper chars, e.g. MABENDECRFDME
func GenUpNum ¶
func GenUpNum() string
Generate a code formated only number and upper chars, e.g. M25ENDE4RF5M
func HashByteThenBase64 ¶
Hash byte array by sha256 and than to base64 string
func HashMD5Check ¶
Hash string by md5 and check write buffer errors
func HashSHA256Hex ¶
Hash byte array by sha256 then encode to hex
func HashThenBase64 ¶
Hash string by sha256 and than to base64 string
func LoadRSAKey ¶
Load RSA private or public key content from the given pem file, and the input buffer size of buffbits must larger than pem file size by call GenRSAKeys to set bits.
func RSA2Sign ¶
Using RSA2 private key to make digital signature, the private key in PKCS#8, ASN.1 DER form.
func RSA2Sign4F ¶
Using RSA2 private key file to make digital signature. the private key in PKCS#8, ASN.1 DER form.
func RSA2Sign4FB64 ¶
Using RSA2 private key file to make digital signature, then format to base64 form, the private key in PKCS#8, ASN.1 DER form.
func RSA2SignB64 ¶
Using RSA2 private key file to make digital signature, then format to base64 form, the private key in PKCS#8, ASN.1 DER form.
func RSA2Verify ¶
Using RSA2 public key to verify PKCS#8, ASN.1 signatured data.
func RSA2Verify4F ¶
Using RSA2 public key to verify PKCS#8, ASN.1 signatured data.
func RSADecrypt ¶
Using RSA private key to decrypt ciphertext.
func RSADecrypt4F ¶
Using RSA private key file to decrypt ciphertext.
func RSAEncrypt ¶
Using RSA public key to encrypt original data.
func RSAEncrypt4F ¶
Using RSA public key file to encrypt original data.
func RSAEncrypt4FB64 ¶
Using RSA public key file to encrypt original data, then format to base64 form.
func RSAEncryptB64 ¶
Using RSA public key to encrypt original data, then format to base64 form.
func RSASign ¶
Using RSA private key to make digital signature, the private key in PKCS#1, ASN.1 DER form.
func RSASign4F ¶
Using RSA private key file to make digital signature, the private key in PKCS#1, ASN.1 DER form.
func RSASign4FB64 ¶
Using RSA private key file to make digital signature, then format to base64 form, the private key in PKCS#1, ASN.1 DER form.
func RSASignB64 ¶
Using RSA private key to make digital signature, then format to base64 form, the private key in PKCS#1, ASN.1 DER form.
func RSAVerify4F ¶
Using RSA public key file to verify PKCS#1 v1.5 signatured data.
func RSAVerifyASN ¶
Using RSA public key to verify ASN.1 signatured data.
func RSAVerifyASN4F ¶
Using RSA public key file to verify ASN.1 signatured data.
func SignSHA256 ¶
Use HmacSHA256 to calculate the signature, and format as base64 string
func ToMD5Hex ¶
Encode multi-input to md5 one string, it same as EncodeMD5 when input only one string.
func ToMD5Lower ¶
Encode string to md5 and then transform to lowers.
func ToMD5Upper ¶
Encode string to md5 and then transform to uppers.
func ViaJwtToken ¶
Verify the encoded jwt token with salt string
Types ¶
type Claims ¶
type Claims struct { Keyword string `json:"keyword"` jwt.RegisteredClaims }
Claims jwt claims data
type SoleCoder ¶
type SoleCoder struct {
// contains filtered or unexported fields
}
Random coder to generate unique number code
`USEAGE` :
coder := mvc.NewSoleCoder() code, _ := coder.Gen(6) logger.I("6 chars code:", code) code, _ = coder.Gen(8) logger.I("8 chars code:", code) code, _ := coder.Gen(6, 5) logger.I("max retry 5 times, 6 chars code:", code) code, _ = coder.Gen(8, 5) logger.I("max retry 5 times, 8 chars code:", code)
func NewSoleCoder ¶
Create SoleCoder and init with exist codes