github.com/turingchain2020/turingchain@v1.1.21/wallet/common/crypto.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package common
     6  
     7  import (
     8  	"crypto/aes"
     9  	"crypto/cipher"
    10  )
    11  
    12  // CBCEncrypterPrivkey 使用钱包的password对私钥进行aes cbc加密,返回加密后的privkey
    13  func CBCEncrypterPrivkey(password []byte, privkey []byte) []byte {
    14  	key := make([]byte, 32)
    15  	Encrypted := make([]byte, len(privkey))
    16  	if len(password) > 32 {
    17  		key = password[0:32]
    18  	} else {
    19  		copy(key, password)
    20  	}
    21  
    22  	block, err := aes.NewCipher(key)
    23  	if err != nil {
    24  		return nil
    25  	}
    26  	iv := key[:block.BlockSize()]
    27  
    28  	encrypter := cipher.NewCBCEncrypter(block, iv)
    29  	encrypter.CryptBlocks(Encrypted, privkey)
    30  
    31  	return Encrypted
    32  }
    33  
    34  // CBCDecrypterPrivkey 使用钱包的password对私钥进行aes cbc解密,返回解密后的privkey
    35  func CBCDecrypterPrivkey(password []byte, privkey []byte) []byte {
    36  	key := make([]byte, 32)
    37  	if len(password) > 32 {
    38  		key = password[0:32]
    39  	} else {
    40  		copy(key, password)
    41  	}
    42  	block, err := aes.NewCipher(key)
    43  	if err != nil {
    44  		return nil
    45  	}
    46  	iv := key[:block.BlockSize()]
    47  	decryptered := make([]byte, len(privkey))
    48  	decrypter := cipher.NewCBCDecrypter(block, iv)
    49  	decrypter.CryptBlocks(decryptered, privkey)
    50  	return decryptered
    51  }