zoukankan      html  css  js  c++  java
  • golang Aes

    package models
    
    import (
        "bytes"
        "crypto/aes"
        "crypto/cipher"
        "errors"                                                                                                                                                                 
    )
    
    const (
        ivDefValue = "0102030405060708"
    )
    
    func AesEncrypt(plaintext []byte, key []byte) ([]byte, error) {
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, errors.New("invalid decrypt key")
        }   
        blockSize := block.BlockSize()
        plaintext = PKCS5Padding(plaintext, blockSize)
        iv := []byte(ivDefValue)
        blockMode := cipher.NewCBCEncrypter(block, iv) 
    
        ciphertext := make([]byte, len(plaintext))
        blockMode.CryptBlocks(ciphertext, plaintext)
    
        return ciphertext, nil 
    }
    
    func AesDecrypt(ciphertext []byte, key []byte) ([]byte, error) {
    
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, errors.New("invalid decrypt key")
        }   
    
        blockSize := block.BlockSize()
    
        if len(ciphertext) < blockSize {
            return nil, errors.New("ciphertext too short")
        }   
    
        iv := []byte(ivDefValue)
        if len(ciphertext)%blockSize != 0 { 
            return nil, errors.New("ciphertext is not a multiple of the block size")
        }   
    
        blockModel := cipher.NewCBCDecrypter(block, iv)
    
        plaintext := make([]byte, len(ciphertext))
        blockModel.CryptBlocks(plaintext, ciphertext)
        plaintext = PKCS5UnPadding(plaintext)
    
        return plaintext, nil
    }
    
    func PKCS5Padding(src []byte, blockSize int) []byte {
        padding := blockSize - len(src)%blockSize
        padtext := bytes.Repeat([]byte{byte(padding)}, padding)
        return append(src, padtext...)
    }
    
    func PKCS5UnPadding(src []byte) []byte {
        length := len(src)
        unpadding := int(src[length-1])
        if length - unpadding <= 0 {
            return src
        }
        return src[:(length - unpadding)]
    } 
    

      

  • 相关阅读:
    第二节:如何正确使用WebApi和使用过程中的一些坑
    nodejs中function*、yield和Promise的示例
    关于nodejs访问mysql的思考
    nodejs使用log4js记录日志
    nodejs初识
    Spring学习笔记(入门)
    mybatis使用注解开发
    MyBatis配置文件中的常用配置
    using 自动释放资源示例
    Java将byte[]和int的互相转换
  • 原文地址:https://www.cnblogs.com/allenhaozi/p/5762890.html
Copyright © 2011-2022 走看看