secure

package
v0.0.0-...-6058dde Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2024 License: Apache-2.0 Imports: 28 Imported by: 0

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

View Source
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;
}
View Source
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

func AESDecrypt(secretkey []byte, ciphertextb64 string) (string, error)

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

func AESEncrypt(secretkey, original []byte) (string, error)

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

func Base64ToByte(ciphertext string) ([]byte, error)

Decode base64 string to byte array

func ByteToBase64

func ByteToBase64(original []byte) string

Encode byte array to base64 string

func DecClaims

func DecClaims(keyword string, count ...int) ([]string, error)

Decode claims of jwt token and return datas as string array

func DecJwtKeyword deprecated

func DecJwtKeyword(keyword string) (string, string, string)

Decode account uuid, password and subject from jwt keyword string

Deprecated: Please use DecClaims() instead

func DecodeBase64

func DecodeBase64(ciphertext string) (string, error)

Decode from base64 string

func ECCHashSignB64

func ECCHashSignB64(hash []byte, prikeyb64 string) (string, error)

Use ECC to sign hash data to base64 string by given origin private key text

func ECCHashVerifyB64

func ECCHashVerifyB64(hash []byte, pubkeyb64 string, rsb64 string) (bool, error)

Use ECC public key and rs data to verify given hash data

func EncClaims

func EncClaims(uuid string, params ...string) string

Encode account uuid and optianl datas as claims content of jwt token

func EncJwtKeyword deprecated

func EncJwtKeyword(uuid, pwd string, subject string) string

Encode account uuid, password and subject string

Deprecated: Please use EncClaims() instead

func EncodeB64MD5

func EncodeB64MD5(original string) string

Encode string to base64, and then encode by md5

func EncodeBase64

func EncodeBase64(original string) string

Encode string by base64

func EncodeMD5

func EncodeMD5(original string) string

Encode string by md5, it ignore write buffer errors

func EncodeMD5B64

func EncodeMD5B64(original string) string

Encode string to md5, and then encode by base64

func EncodeMD5Check

func EncodeMD5Check(original string) (string, error)

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

func GCMEncrypt(secretkey, original []byte, additional ...[]byte) (string, string, error)

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 GenAESKey

func GenAESKey() string

Generate AES key range chars in [0-9a-z]{16}

func GenCode

func GenCode() string

Generate a code by using current nanosecond, e.g. M25eNdE4rF5

func GenCodeFrom

func GenCodeFrom(src int64) string

Generate a code from given int64 data, e.g. M25eNdE4rF5

func GenECCPriKey

func GenECCPriKey(prikey string) (*ecdsa.PrivateKey, error)

Generate a ECC private key by origin key text

func GenECCPriKeyB64

func GenECCPriKeyB64(prikeyb64 string) (*ecdsa.PrivateKey, error)

Generate a ECC private key by base64 formated key text

func GenECCPubKey

func GenECCPubKey(pubkey string) (*ecdsa.PublicKey, error)

Generate a ECC public key by origin key text

func GenECCPubKeyB64

func GenECCPubKeyB64(pubkeyb64 string) (*ecdsa.PublicKey, error)

Generate a ECC public key by base64 formated key text

func GenECCShareKeys

func GenECCShareKeys(pub *ecdsa.PublicKey, priD *big.Int) (*big.Int, *big.Int)

Generate ECC shared keys by ECC public key and private digital signature

func GenEccShareKeysHash

func GenEccShareKeysHash(prikey, pubkey string) ([]byte, error)

Generate ECC share keys hash data by origin private and public key

func GenEccShareKeysHashB64

func GenEccShareKeysHashB64(prikeyb64, pubkeyb64 string) ([]byte, error)

Generate ECC share keys hash data by base64 formated private and public key

func GenHash

func GenHash(src, salt string, buflen ...int) (string, error)

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

func GenJwtToken(keyword, salt string, dur time.Duration) (string, error)

Generate a jwt token with keyword and salt string, the token will expired after the given duration

func GenLoginToken

func GenLoginToken(acc, pwd string) string

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 GenNonce

func GenNonce() string

Generate a random num and convert to string

func GenOAuthCode

func GenOAuthCode(length int, randomType string) (string, error)

Generate a random OAuth code

func GenRSAKeys

func GenRSAKeys(bits int) (string, string, error)

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 GenRSFromB2BI

func GenRSFromB2BI(sign []byte) (*big.Int, *big.Int)

Generate R and S from sign data

func GenRandCode

func GenRandCode() string

Generate a code by using current nanosecond and append random suffix, e.g. M25eNdE4rF50987

func GenRandCodeFrom

func GenRandCodeFrom(src int64) string

Generate a code from given int64 data and append random suffix, e.g. M25eNdE4rF50987

func GenRandUUID

func GenRandUUID(buflen ...int) string

Generate a random number uuid with specified digits

func GenSalt

func GenSalt(buflen ...int) (string, error)

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 GenToken

func GenToken(original string) string

Convert to lower string and encode by base64 -> md5

func GenUUID

func GenUUID() int64

Generate a new uuid in int64

func GenUUIDString

func GenUUIDString() string

Generate a new uuid in 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

func HashByteThenBase64(data []byte) string

Hash byte array by sha256 and than to base64 string

func HashMD5

func HashMD5(original []byte) []byte

Hash string by md5, it ignore write buffer errors

func HashMD5Check

func HashMD5Check(original []byte) ([]byte, error)

Hash string by md5 and check write buffer errors

func HashSHA256

func HashSHA256(original []byte) []byte

Hash byte array by sha256

func HashSHA256Hex

func HashSHA256Hex(original []byte) string

Hash byte array by sha256 then encode to hex

func HashSHA256String

func HashSHA256String(original string) []byte

Hash string by sha256

func HashThenBase64

func HashThenBase64(data string) string

Hash string by sha256 and than to base64 string

func LoadRSAKey

func LoadRSAKey(filepath string, buffbits ...int) ([]byte, error)

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 MD5Lower

func MD5Lower(original string) string

Encode string to md5 and then transform to lowers without check error.

func MD5Upper

func MD5Upper(original string) string

Encode string to md5 and then transform to uppers without check error.

func RSA2Sign

func RSA2Sign(prikey, original []byte) ([]byte, error)

Using RSA2 private key to make digital signature, the private key in PKCS#8, ASN.1 DER form.

func RSA2Sign4F

func RSA2Sign4F(prifile string, original []byte) ([]byte, error)

Using RSA2 private key file to make digital signature. the private key in PKCS#8, ASN.1 DER form.

func RSA2Sign4FB64

func RSA2Sign4FB64(prifile string, original []byte) (string, error)

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

func RSA2SignB64(prikey, original []byte) (string, error)

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

func RSA2Verify(pubkey, original, signature []byte) error

Using RSA2 public key to verify PKCS#8, ASN.1 signatured data.

func RSA2Verify4F

func RSA2Verify4F(pubfile string, original, signature []byte) error

Using RSA2 public key to verify PKCS#8, ASN.1 signatured data.

func RSADecrypt

func RSADecrypt(prikey, ciphertext []byte) ([]byte, error)

Using RSA private key to decrypt ciphertext.

func RSADecrypt4F

func RSADecrypt4F(prifile string, ciphertext []byte) ([]byte, error)

Using RSA private key file to decrypt ciphertext.

func RSAEncrypt

func RSAEncrypt(pubkey, original []byte) ([]byte, error)

Using RSA public key to encrypt original data.

func RSAEncrypt4F

func RSAEncrypt4F(pubfile string, original []byte) ([]byte, error)

Using RSA public key file to encrypt original data.

func RSAEncrypt4FB64

func RSAEncrypt4FB64(pubfile string, original []byte) (string, error)

Using RSA public key file to encrypt original data, then format to base64 form.

func RSAEncryptB64

func RSAEncryptB64(pubkey, original []byte) (string, error)

Using RSA public key to encrypt original data, then format to base64 form.

func RSASign

func RSASign(prikey, original []byte) ([]byte, error)

Using RSA private key to make digital signature, the private key in PKCS#1, ASN.1 DER form.

func RSASign4F

func RSASign4F(prifile string, original []byte) ([]byte, error)

Using RSA private key file to make digital signature, the private key in PKCS#1, ASN.1 DER form.

func RSASign4FB64

func RSASign4FB64(prifile string, original []byte) (string, error)

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

func RSASignB64(prikey, original []byte) (string, error)

Using RSA private key to make digital signature, then format to base64 form, the private key in PKCS#1, ASN.1 DER form.

func RSAVerify

func RSAVerify(pubkey, original, signature []byte) error

Using RSA public key to verify PKCS#1 v1.5 signatured data.

func RSAVerify4F

func RSAVerify4F(pubfile string, original, signature []byte) error

Using RSA public key file to verify PKCS#1 v1.5 signatured data.

func RSAVerifyASN

func RSAVerifyASN(pubkey, original, signature []byte) error

Using RSA public key to verify ASN.1 signatured data.

func RSAVerifyASN4F

func RSAVerifyASN4F(pubfile string, original, signature []byte) error

Using RSA public key file to verify ASN.1 signatured data.

func SignSHA1

func SignSHA1(securekey string, src string) string

Use HmacSHA1 to calculate the signature, and format as base64 string

func SignSHA256

func SignSHA256(securekey string, src string) string

Use HmacSHA256 to calculate the signature, and format as base64 string

func ToMD5Hex

func ToMD5Hex(input ...string) string

Encode multi-input to md5 one string, it same as EncodeMD5 when input only one string.

func ToMD5Lower

func ToMD5Lower(original string) (string, error)

Encode string to md5 and then transform to lowers.

func ToMD5Upper

func ToMD5Upper(original string) (string, error)

Encode string to md5 and then transform to uppers.

func ViaJwtToken

func ViaJwtToken(signedToken, salt string) (string, error)

Verify the encoded jwt token with salt string

func ViaLoginToken

func ViaLoginToken(acc, pwd, token string, duration int64) (bool, error)

Verify login token.

---

      token => base64
                 |
       +------- "."---------|
      md5                base64
       |                    |
    base64          current nanosecode
       |
    |- + -|
account   password

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

func NewSoleCoder(data ...[]string) *SoleCoder

Create SoleCoder and init with exist codes

func (*SoleCoder) Gen

func (c *SoleCoder) Gen(codelen int, times ...int) (string, error)

Generate a given length number code, it may throw a error when over the retry times

func (*SoleCoder) Remove

func (c *SoleCoder) Remove(code string)

Remove used sole code outof cache

Jump to

Keyboard shortcuts

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