-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecccrypt.go
74 lines (68 loc) · 1.73 KB
/
ecccrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package goEncrypt
import (
"log"
"crypto/rand"
"encoding/pem"
"runtime"
"crypto/x509"
"crypto/ecdsa"
)
/*
@Time : 2018/11/4 16:43
@Author : wuman
@File : EccCrypt
@Software: GoLand
*/
func init(){
log.SetFlags(log.Ldate|log.Lshortfile)
}
// The public key and plaintext are passed in for encryption
func EccEncrypt(plainText,key []byte)( cryptText []byte,err error){
block, _:= pem.Decode(key)
defer func(){
if err:=recover();err!=nil{
switch err.(type){
case runtime.Error:
log.Println("runtime err:",err,"Check that the key is correct")
default:
log.Println("error:",err)
}
}
}()
tempPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err!=nil{
return nil,err
}
// Decode to get the private key in the ecdsa package
publicKey1:=tempPublicKey.(*ecdsa.PublicKey)
// Convert to the public key in the ecies package in the ethereum package
publicKey:=ImportECDSAPublic(publicKey1)
crypttext,err:=Encrypt(rand.Reader, publicKey, plainText, nil, nil)
return crypttext,err
}
// The private key and plaintext are passed in for decryption
func EccDecrypt(cryptText,key []byte)( msg []byte,err error){
block, _:= pem.Decode(key)
defer func(){
if err:=recover();err!=nil{
switch err.(type){
case runtime.Error:
log.Println("runtime err:",err,"Check that the key is correct")
default:
log.Println("error:",err)
}
}
}()
tempPrivateKey, err := x509.ParseECPrivateKey(block.Bytes)
if err!=nil{
return nil,err
}
// Decode to get the private key in the ecdsa package
// Convert to the private key in the ecies package in the ethereum package
privateKey:=ImportECDSA(tempPrivateKey)
plainText,err:=privateKey.Decrypt(cryptText,nil,nil)
if err!=nil{
return nil,err
}
return plainText,nil
}