加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang1.7.3使用标准库的AES加密解密不实用扩展协议

发布时间:2020-12-16 18:23:55 所属栏目:大数据 来源:网络整理
导读:package mainimport ( "crypto/aes" "crypto/cipher" "fmt" )type tobytes struct { cip cipher.Block pdgtext [] byte }func main() { cip,_ := aes.NewCipher([] byte ( "1234567891234567" )) enc := tobytes{cip: cip,pdgtext: make([] byte ,cip.BlockS
package main

import (
    "crypto/aes"
    "crypto/cipher"
    "fmt"
)

type tobytes struct {
    cip     cipher.Block
    pdgtext []byte
}

func main() {
    cip,_ := aes.NewCipher([]byte("1234567891234567"))
    enc := &tobytes{cip: cip,pdgtext: make([]byte,cip.BlockSize())}
    src := enc.Encrypt([]byte("czxichen"))
    dst := enc.Decrypt(src)
    fmt.Println(string(dst))
}
 //使用AES加密文本,加密的文本不能为空
func (a *tobytes) Encrypt(src []byte) (dst []byte) {
    src = a.padding(src)
    dst = make([]byte,len(src))
    var index int = 0
    for len(src) > 0 {
        a.cip.Encrypt(dst[index:index+a.cip.BlockSize()],src)
        index += a.cip.BlockSize()
        src = src[a.cip.BlockSize():]
    }
    return dst
}
 //使用AES解密文本
func (a *tobytes) Decrypt(src []byte) (dst []byte) {
    if len(src)%a.cip.BlockSize() != 0 {
        return src
    }
    dst = make([]byte,len(src))
    var index int = 0
    for len(src) > 0 {
        a.cip.Decrypt(dst[index:index+a.cip.BlockSize()],src)
        index += a.cip.BlockSize()
        src = src[a.cip.BlockSize():]
    }
    return a.unpadding(dst)
}
 //使用AES加密文本的时候文本必须定长,即必须是16,24,32的整数倍,
func (a *tobytes) padding(src []byte) (dst []byte) {
    pdg := a.cip.BlockSize() - len(src)%a.cip.BlockSize()
    p := a.pdgtext[:pdg]
    p[pdg-1] = byte(pdg)
    return append(src,p...)
}
 //使用AES解密文本,解密收删除padding的文本
func (a *tobytes) unpadding(src []byte) (dst []byte) {
    length := len(src)
    if length <= 0 {
        return src
    }
    return src[:(length - int(src[length-1]))]
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读