Coder Social home page Coder Social logo

forgoer / openssl Goto Github PK

View Code? Open in Web Editor NEW
279.0 7.0 47.0 44 KB

A functions wrapping of OpenSSL library for symmetric and asymmetric encryption and decryption.

License: Apache License 2.0

Go 100.00%
aes des openssl encryption cbc ecb aes-encryption aes-cbc aes-256 rsa

openssl's Introduction

Openssl encryption

Go Report Card Default Coverage Status Godoc Release

A functions wrapping of OpenSSL library for symmetric and asymmetric encryption and decryption

Installation

The only requirement is the Go Programming Language

go get -u github.com/forgoer/openssl

Usage

AES

The length of the key can be 16/24/32 characters (128/192/256 bits)

AES-ECB:

src := []byte("123456")
key := []byte("1234567890123456")
dst , _ := openssl.AesECBEncrypt(src, key, openssl.PKCS7_PADDING)
fmt.Printf(base64.StdEncoding.EncodeToString(dst))  // yXVUkR45PFz0UfpbDB8/ew==

dst , _ = openssl.AesECBDecrypt(dst, key, openssl.PKCS7_PADDING)
fmt.Println(string(dst)) // 123456

AES-CBC:

src := []byte("123456")
key := []byte("1234567890123456")
iv := []byte("1234567890123456")
dst , _ := openssl.AesCBCEncrypt(src, key, iv, openssl.PKCS7_PADDING)
fmt.Println(base64.StdEncoding.EncodeToString(dst)) // 1jdzWuniG6UMtoa3T6uNLA==

dst , _ = openssl.AesCBCDecrypt(dst, key, iv, openssl.PKCS7_PADDING)
fmt.Println(string(dst)) // 123456

DES

The length of the key must be 8 characters (64 bits).

DES-ECB:

openssl.DesECBEncrypt(src, key, openssl.PKCS7_PADDING)
openssl.DesECBDecrypt(src, key, openssl.PKCS7_PADDING)

DES-CBC:

openssl.DesCBCEncrypt(src, key, iv, openssl.PKCS7_PADDING)
openssl.DesCBCDecrypt(src, key, iv, openssl.PKCS7_PADDING)

3DES

The length of the key must be 24 characters (192 bits).

3DES-ECB:

openssl.Des3ECBEncrypt(src, key, openssl.PKCS7_PADDING)
openssl.Des3ECBDecrypt(src, key, openssl.PKCS7_PADDING)

3DES-CBC:

openssl.Des3CBCEncrypt(src, key, iv, openssl.PKCS7_PADDING)
openssl.Des3CBCDecrypt(src, key, iv, openssl.PKCS7_PADDING)

RSA

openssl.RSAGenerateKey(bits int, out io.Writer)
openssl.RSAGeneratePublicKey(priKey []byte, out io.Writer)

openssl.RSAEncrypt(src, pubKey []byte) ([]byte, error)
openssl.RSADecrypt(src, priKey []byte) ([]byte, error)

openssl.RSASign(src []byte, priKey []byte, hash crypto.Hash) ([]byte, error)
openssl.RSAVerify(src, sign, pubKey []byte, hash crypto.Hash) error

HMAC-SHA

// Sha1 Calculate the sha1 hash of a string
Sha1(str string) []byte

// HmacSha1 Calculate the sha1 hash of a string using the HMAC method
HmacSha1(key string, data string) []byte

// HmacSha1ToString Calculate the sha1 hash of a string using the HMAC method, outputs lowercase hexits
HmacSha1ToString(key string, data string) string

// Sha256 Calculate the sha256 hash of a string
Sha256(str string) []byte

// HmacSha256 Calculate the sha256 hash of a string using the HMAC method
HmacSha256(key string, data string) []byte

// HmacSha256ToString Calculate the sha256 hash of a string using the HMAC method, outputs lowercase hexits
HmacSha256ToString(key string, data string) string

License

This project is licensed under the Apache 2.0 license.

Contact

If you have any issues or feature requests, please contact us. PR is welcomed.

openssl's People

Contributors

conero avatar fosmjo avatar leeqvip avatar woorui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

openssl's Issues

Uncaught panic

Hi, author.

There is an uncaught panic popups from code

https://github.com/forgoer/openssl/blob/master/cbc.go#L35

mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(dst, src)

making calls to openssl.Des3CBCDecrypt throws panic too.

Can you handle this panic into an error within this library, people cannot control their decoding data from internet are always valid.

AesECBDecrypt will panic if invalid src or key

AesECBDecrypt will panic if source string or key string is invalid.
You can replicate by changing function TestAesECBDecrypt of test file aes_test.go, in AES-256-ECB, PKCS7_PADDING, change any one character of either src, or key, it will cause panic: runtime error: slice bounds out of range.

func PKCS7UnPadding(src []byte) []byte {
	length := len(src)
	unpadding := int(src[length-1])
	return src[:(length - unpadding)]
}

Reason is unpadding is greater than length. Suggestion is to add some input validation, or check length - unpadding must be non-negative.

Encryption/Decryption does work properly using the library but fails using OpenSSL CLI

Here is my class:

package utils

import (
    "github.com/forgoer/openssl"
)

type Crypter struct {
    key []byte
    iv  []byte
}

func NewCrypter(key []byte, iv []byte) (*Crypter, error) {
    return &Crypter{key: key, iv: iv}, nil
}

func (c *Crypter) Encrypt(data []byte) ([]byte, error) {
    return openssl.AesCBCEncrypt(data, c.key, c.iv, openssl.PKCS7_PADDING)
}

func (c *Crypter) Decrypt(data []byte) ([]byte, error) {
    return openssl.AesCBCDecrypt(data, c.key, c.iv, openssl.PKCS7_PADDING)
}

The class is used with following iv and key.

func EncryptFileWithSharedKey(fullname string, sharedKey string) (encryptedFile []byte, err error) {

key := []byte("1234567890123456")
iv := []byte("1234567890123456")

// Initialize new crypter struct. Errors are ignored.
crypter, _ := NewCrypter(key, iv)

// Open the file.
file, err := os.Open(fullname)
if err != nil {
	log.Log.Error(err.Error())
	return
}
defer file.Close()

by, _ := ioutil.ReadAll(file)
encryptedFile, err = crypter.Encrypt(by)

return
}

Encryption and decryption does work properly for my files. However when encrypting using the library and decrypting through the traditional OpenSSL CLI does not work. Not sure if I'm missing something.

% openssl enc -d -aes-256-cbc -in file_enc.mp4 -out file_dec.mp4 -a -iv 1234567890123456 -K 1234567890123456
hex string is too short, padding with zero bytes to length
hex string is too short, padding with zero bytes to length
bad decrypt
8632832704:error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:crypto/evp/evp_enc.c:601:

I noticed that when encrypting through % openssl enc -aes-256-cbc -in .. the Salt__ prefix is added to the encrypted file, whereas with the library it isn't.

Cannot get latest version: module contains a go.mod file, so module path should be github.com/forgoer/openssl/v2

Background

The github.com/forgoer/openssl uses Go modules and the current release version is v2. And it’s module path is "github.com/forgoer/openssl", instead of "github.com/forgoer/openssl/v2". It must comply with the specification of "Releasing Modules for v2 or higher" available in the Modules documentation. Quoting the specification:

A package that has opted in to modules must include the major version in the import path to import any v2+ modules
To preserve import compatibility, the go command requires that modules with major version v2 or later use a module path with that major version as the final element. For example, version v2.0.0 of example.com/m must instead use module path example.com/m/v2.
https://github.com/golang/go/wiki/Modules#releasing-modules-v2-or-higher

Steps to Reproduce

GO111MODULE=on, run go get targeting any version >= v2.0.0 of the forgoer/openssl:

$ go get github.com/forgoer/[email protected]
go: finding github.com/forgoer/openssl v2.0.0
go: finding github.com/forgoer/openssl v2.0.0
go get github.com/forgoer/[email protected]: github.com/forgoer/[email protected]: invalid version: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v2

SO anyone using Go modules will not be able to easily use any newer version of forgoer/openssl.

Solution

1. Kill the go.mod files, rolling back to GOPATH.

This would push them back to not being managed by Go modules (instead of incorrectly using Go modules).
Ensure compatibility for downstream module-aware projects and module-unaware projects projects

2. Fix module path to strictly follow SIV rules.

Patch the go.mod file to declare the module path as github.com/forgoer/openssl/v2 as per the specs. And adjust all internal imports.
The downstream projects might be negatively affected in their building if they are module-unaware (Go versions older than 1.9.7 and 1.10.3; Or use third-party dependency management tools, such as: Dep, glide,govendor…).

If you don't want to break the above repos. This method can provides better backwards-compatibility.
Release a v2 or higher module through the major subdirectory strategy: Create a new v2 subdirectory (github.com/forgoer/openssl/v2) and place a new go.mod file in that subdirectory. The module path must end with /v2. Copy or move the code into the v2 subdirectory. Update import statements within the module to also use /v2 (import "github.com/forgoer/openssl/v2/…"). Tag the release with v2.x.y.

3. Suggest your downstream module users use hash instead of a version tag.

If the standard rule of go modules conflicts with your development mode. Or not intended to be used as a library and does not make any guarantees about the API. So you can’t comply with the specification of "Releasing Modules for v2 or higher" available in the Modules documentation.
Regardless, since it's against one of the design choices of Go, it'll be a bit of a hack. Instead of go get github.com/forgoer/openssl@version-tag, module users need to use this following way to get the forgoer/openssl:
(1) Search for the tag you want (in browser)
(2) Get the commit hash for the tag you want
(3) Run go get github.com/forgoer/openssl@commit-hash
(4) Edit the go.mod file to put a comment about which version you actually used
This will make it difficult for module users to get and upgrade forgoer/openssl.

[*] You can see who will be affected here: [11 module users, e.g., outman/abucket, oyjjpp/algorithm, sirodeneko/NeteaseCloudMusicApiWithGo]
https://github.com/search?q=forgoer%2Fopenssl+filename%3Ago.mod&type=Code

Summary

You can make a choice to fix DM issues by balancing your own development schedules/mode against the affects on the downstream projects.

For this issue, Solution 2 can maximize your benefits and with minimal impacts to your downstream projects the ecosystem.

References

发个新版本吧

希望打个tag发布一个新版本。
master 现在的代码和v1有不少区别了。v1有bug。
v1这个部分有bug,加密结果会有多余00000,而master这部分逻辑已经换了。

func ECBEncrypt(block cipher.Block, src, key []byte, padding string) ([]byte, error) {
	blockSize := block.BlockSize()
	src = Padding(padding, src, blockSize)

	encryptData := make([]byte, len(src))
	tmpData := make([]byte, blockSize)

	for index := 0; index < len(src); index += blockSize {
		block.Encrypt(tmpData, src[index:index+blockSize])
		copy(encryptData, tmpData)
	}
	return encryptData, nil
}

The encrypted data cannot be decrypted after being decoded after base64 and hex

sendpix0

error info

`panic: crypto/cipher: input not full blocks

goroutine 1 [running]:
crypto/cipher.(*cbcDecrypter).CryptBlocks(0x513918?, {0xc000016390?, 0xc000016330?, 0x10?}, {0xc0000181f8?, 0xc000131f30?, 0x10?})
/usr/local/go/src/crypto/cipher/cbc.go:119 +0x478
github.com/forgoer/openssl.CBCDecrypt({0x513918, 0xc00007e6f0}, {0xc0000181f8, 0xf, 0x12}, {0xc000016330, 0x10, 0x10}, {0x4ef031, 0x5})
/root/.local/go/pkg/mod/github.com/forgoer/[email protected]/cbc.go:35 +0x103
github.com/forgoer/openssl.AesCBCDecrypt({0xc0000181f8, 0xf, 0x12}, {0xc000131f30?, 0xc000131ed0?, 0x19?}, {0xc000016330, 0x10, 0x10}, {0x4ef031, ...})
/root/.local/go/pkg/mod/github.com/forgoer/[email protected]/aes.go:43 +0xb6
main.AesCBCDecrypt({0xc000131f30, 0x10, 0x10}, {0xc000016330, 0x10, 0x10}, {0xc0000181c8?, 0xc0000021a0?})
/root/bbb/main.go:21 +0x9c
main.main()
/root/bbb/main.go:33 +0x12c
exit status 2`

It's OK to remove hex and base64

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.