本文整理汇总了Golang中crypto/elliptic.Marshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Marshal函数的具体用法?Golang Marshal怎么用?Golang Marshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Marshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Encrypt
// Encrypt plainText into an Encrypted Message using the given public key.
func Encrypt(log chan string, dest_pubkey []byte, plainText string) *EncryptedMessage {
// Generate New Public/Private Key Pair
D1, X1, Y1 := CreateKey(log)
// Unmarshal the Destination's Pubkey
X2, Y2 := elliptic.Unmarshal(elliptic.P256(), dest_pubkey)
// Point Multiply to get new Pubkey
PubX, PubY := elliptic.P256().ScalarMult(X2, Y2, D1)
// Generate Pubkey hashes
PubHash := sha512.Sum512(elliptic.Marshal(elliptic.P256(), PubX, PubY))
PubHash_E := PubHash[:32]
PubHash_M := PubHash[32:64]
IV, cipherText, _ := SymmetricEncrypt(PubHash_E, plainText)
// Generate HMAC
mac := hmac.New(sha256.New, PubHash_M)
mac.Write(cipherText)
HMAC := mac.Sum(nil)
ret := new(EncryptedMessage)
copy(ret.IV[:], IV[:])
copy(ret.PublicKey[:], elliptic.Marshal(elliptic.P256(), X1, Y1))
ret.CipherText = cipherText
copy(ret.HMAC[:], HMAC)
return ret
}
示例2: TestMessageCleartextSignRecover
// Tests whether a message can be signed, and wrapped in plain-text.
func TestMessageCleartextSignRecover(t *testing.T) {
key, err := crypto.GenerateKey()
if err != nil {
t.Fatalf("failed to create crypto key: %v", err)
}
payload := []byte("hello world")
msg := NewMessage(payload)
if _, err := msg.Wrap(DefaultPoW, Options{
From: key,
}); err != nil {
t.Fatalf("failed to sign message: %v", err)
}
if msg.Flags&signatureFlag != signatureFlag {
t.Fatalf("signature flag mismatch: have %d, want %d", msg.Flags&signatureFlag, signatureFlag)
}
if bytes.Compare(msg.Payload, payload) != 0 {
t.Fatalf("payload mismatch after signing: have 0x%x, want 0x%x", msg.Payload, payload)
}
pubKey := msg.Recover()
if pubKey == nil {
t.Fatalf("failed to recover public key")
}
p1 := elliptic.Marshal(crypto.S256(), key.PublicKey.X, key.PublicKey.Y)
p2 := elliptic.Marshal(crypto.S256(), pubKey.X, pubKey.Y)
if !bytes.Equal(p1, p2) {
t.Fatalf("public key mismatch: have 0x%x, want 0x%x", p2, p1)
}
}
示例3: MarshalMark
func MarshalMark(c elliptic.Curve, m *Mark) []byte {
bytelen := (c.Params().BitSize + 7) >> 3
pointlen := 1 + 2*bytelen
outlen := 2 * pointlen
ret := make([]byte, outlen, outlen)
abytes := elliptic.Marshal(c, m.ax, m.ay)
copy(ret, abytes)
bbytes := elliptic.Marshal(c, m.bx, m.by)
copy(ret[pointlen:], bbytes)
return ret
}
示例4: GenerateKeypair
// GenerateKeypair generates a public and private ECDSA key, for
// later user with NewIssuer or NewVerifier. These are written
// as binary files, because PEM is pointless.
func GenerateKeypair(filename string) (err error) {
priv, err := ecdsa.GenerateKey(curveEll, rand.Reader)
if err != nil {
return
}
err = ioutil.WriteFile(filename+".priv", elliptic.Marshal(curveEll, priv.x, priv.y), FileMode(0600))
if err != nil {
return
}
err = ioutil.WriteFile(filename+".pub", elliptic.Marshal(curveEll, pub.x, pub.y), FileMode(0644))
return
// TODO(dlg): also write out JWK
}
示例5: cmpPublic
// cmpPublic returns true if the two public keys represent the same pojnt.
func cmpPublic(pub1, pub2 PublicKey) bool {
if pub1.X == nil || pub1.Y == nil {
fmt.Println(ErrInvalidPublicKey.Error())
return false
}
if pub2.X == nil || pub2.Y == nil {
fmt.Println(ErrInvalidPublicKey.Error())
return false
}
pub1Out := elliptic.Marshal(pub1.Curve, pub1.X, pub1.Y)
pub2Out := elliptic.Marshal(pub2.Curve, pub2.X, pub2.Y)
return bytes.Equal(pub1Out, pub2Out)
}
示例6: FillBallot
func FillBallot(c elliptic.Curve, px *big.Int, py *big.Int, entry int,
size int) *Ballot {
b := new(Ballot)
b.boxes = make([]*Checkbox, size, size)
for i := 0; i < size; i++ {
if i == entry {
b.boxes[i] = VoteOne(c, px, py)
} else {
b.boxes[i] = VoteZero(c, px, py)
}
}
//TODO: add validation
//Let A be the sum of all the A, B the sum of all the B
//Then we want log_g(A)=log_h(B-g)
ax := big.NewInt(0)
ay := big.NewInt(0)
bx := big.NewInt(0)
by := big.NewInt(0)
s := big.NewInt(0)
for i := 0; i < size; i++ {
ax, ay = c.Add(ax, ay, b.boxes[i].ax, b.boxes[i].ay)
bx, by = c.Add(bx, by, b.boxes[i].bx, b.boxes[i].by)
s.Add(s, b.boxes[i].s)
}
s.Mod(s, c.Params().N)
k, err := rand.Int(rand.Reader, c.Params().N)
if err != nil {
panic("Not here, not now")
}
v1x, v1y := c.ScalarBaseMult(k.Bytes())
v2x, v2y := c.ScalarMult(px, py, k.Bytes())
var commit [4][]byte
commit[0] = elliptic.Marshal(c, ax, ay)
commit[1] = elliptic.Marshal(c, bx, by)
commit[2] = elliptic.Marshal(c, v1x, v1y)
commit[3] = elliptic.Marshal(c, v2x, v2y)
cb := bytes.Join(commit[:], []byte{})
cbytes := sha256.Sum256(cb[:])
b.c = big.NewInt(0)
b.c.SetBytes(cbytes[:])
b.c.Mod(b.c, c.Params().N)
b.r = big.NewInt(0)
//r=k-c*s
b.r.Mul(b.c, s)
b.r.Sub(k, b.r)
b.r.Mod(b.r, c.Params().N)
return b
}
示例7: marshalECDSASHASigningKeyV1
// marshalECDSASHASigningKeyV1 encodes a private key as a protobuf message.
func marshalECDSASHASigningKeyV1(k *ecdsa.PrivateKey) *ECDSA_SHA_SigningKeyV1 {
return &ECDSA_SHA_SigningKeyV1{
Curve: NamedEllipticCurve_PRIME256_V1.Enum(),
EcPrivate: k.D.Bytes(),
EcPublic: elliptic.Marshal(k.Curve, k.X, k.Y),
}
}
示例8: marshalECDSAKey
func marshalECDSAKey(priv *ecdsa.PrivateKey) (out []byte, err error) {
var eckey ecPrivateKey
eckey.Version = 1
eckey.PrivateKey = priv.D.Bytes()
switch priv.PublicKey.Curve {
case elliptic.P256():
eckey.NamedCurveOID = oidNamedCurveP256
case elliptic.P384():
eckey.NamedCurveOID = oidNamedCurveP384
case elliptic.P521():
eckey.NamedCurveOID = oidNamedCurveP521
default:
err = ErrInvalidPrivateKey
}
pkey := elliptic.Marshal(priv.PublicKey.Curve, priv.PublicKey.X,
priv.PublicKey.Y)
if pkey == nil {
err = ErrInvalidPrivateKey
return
}
eckey.PublicKey = asn1.BitString{
BitLength: len(pkey) * 8,
Bytes: pkey,
}
out, err = asn1.Marshal(eckey)
return
}
示例9: HandleRegisterBasic
func HandleRegisterBasic(w http.ResponseWriter, r *http.Request) {
fmt.Println("HandleRegisterBasic")
tmpCurve := elliptic.P256()
r.ParseMultipartForm(int64(100))
step := strings.TrimSpace(r.PostFormValue("step"))
//state := strings.TrimSpace(r.PostFormValue("state"))
if step == "0" {
//fmt.Println(step, ":", state)
w.Header().Set("Content-Type", "application/json")
preInfo, _ := json.Marshal(PreInfo{tmpCurve.Params().Gx.String(), tmpCurve.Params().Gy.String(), tmpCurve.Params().P.String(), tmpCurve.Params().B.String(), tmpCurve.Params().N.String()})
//fmt.Println(string(preInfo))
io.WriteString(w, string(preInfo))
}
if step == "1" {
//fmt.Println(step, "::", state)
pubKey := strings.TrimSpace(r.PostFormValue("pub_key"))
fmt.Println(pubKey)
uname := strings.TrimSpace(r.PostFormValue("uname"))
key := strings.Split(pubKey, ",")
pX := new(big.Int)
pY := new(big.Int)
pX.SetString(key[0], 10)
pY.SetString(key[1], 10)
dataB = elliptic.Marshal(tmpCurve, pX, pY)
fmt.Println(">>>>>>>", uname)
fmt.Println(">>>>>>>", dataB)
storeData(uname, dataB)
_, _ = getData(uname)
}
}
示例10: Update
//Update the named content
func (t Tag) Update(hashBytes HID, typeString string) Tag {
t.Parents = Parents{t.Hash()}
t.HashBytes = hashBytes
t.TypeString = typeString
//t.nameSegment = t.nameSegment
t.Version = newVersion()
//t.hkid = t.hkid
prikey, err := geterPoster.getPrivateKeyForHkid(t.Hkid)
if err != nil {
log.Panic("You don't seem to own this Domain")
}
ObjectHash := t.genTagHash(
t.HashBytes,
t.TypeString,
t.NameSegment,
t.Version,
t.Parents,
t.Hkid,
)
ecdsaprikey := ecdsa.PrivateKey(*prikey)
r, s, _ := ecdsa.Sign(rand.Reader, &ecdsaprikey, ObjectHash)
t.Signature = elliptic.Marshal(elliptic.P521(), r, s)
return t
}
示例11: NewTag
//NewTag build a new tag with the initial content
func NewTag(
HashBytes HID,
TypeString string,
nameSegment string,
tparent Parents,
hkid HKID,
) Tag {
prikey, _ := geterPoster.getPrivateKeyForHkid(hkid)
version := newVersion()
if tparent == nil {
tparent = Parents{Blob{}.Hash()}
}
ObjectHash := Tag{}.genTagHash(
HashBytes,
TypeString,
nameSegment,
version,
tparent,
hkid,
)
ecdsaprikey := ecdsa.PrivateKey(*prikey)
r, s, _ := ecdsa.Sign(rand.Reader, &ecdsaprikey, ObjectHash)
signature := elliptic.Marshal(elliptic.P521(), r, s)
t := Tag{HashBytes,
TypeString,
nameSegment,
version,
tparent,
hkid,
signature}
return t
}
示例12: NewECDSAPublicKey
func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey {
pk := &PublicKey{
CreationTime: creationTime,
PubKeyAlgo: PubKeyAlgoECDSA,
PublicKey: pub,
ec: new(ecdsaKey),
}
switch pub.Curve {
case elliptic.P256():
pk.ec.oid = oidCurveP256
case elliptic.P384():
pk.ec.oid = oidCurveP384
case elliptic.P521():
pk.ec.oid = oidCurveP521
default:
panic("unknown elliptic curve")
}
pk.ec.p.bytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
pk.ec.p.bitLength = uint16(8 * len(pk.ec.p.bytes))
pk.setFingerPrintAndKeyId()
return pk
}
示例13: TestMessage
func TestMessage(t *testing.T) {
log := make(chan string, 100)
priv, x, y := encryption.CreateKey(log)
pub := elliptic.Marshal(elliptic.P256(), x, y)
address := encryption.GetAddress(log, x, y)
msg := new(Message)
msg.AddrHash = MakeHash(address)
msg.TxidHash = MakeHash([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})
msg.Timestamp = time.Now().Round(time.Second)
msg.Content = *encryption.Encrypt(log, pub, "Hello World!")
mBytes := msg.GetBytes()
if mBytes == nil {
fmt.Println("Error Encoding Message!")
t.FailNow()
}
msg2 := new(Message)
msg2.FromBytes(mBytes)
if string(msg2.AddrHash.GetBytes()) != string(msg.AddrHash.GetBytes()) || string(msg2.TxidHash.GetBytes()) != string(msg.TxidHash.GetBytes()) || msg2.Timestamp.Unix() != msg.Timestamp.Unix() {
fmt.Println("Message Header incorrect: ", msg2)
t.FailNow()
}
if string(encryption.Decrypt(log, priv, &msg.Content)[:12]) != "Hello World!" {
fmt.Println("Message content incorrect: ", string(encryption.Decrypt(log, priv, &msg.Content)[:12]))
t.Fail()
}
}
示例14: marshalECDSASHAVerifyingKeyV1
// marshalECDSASHAVerifyingKeyV1 encodes a public key as a protobuf message.
func marshalECDSASHAVerifyingKeyV1(k *ecdsa.PublicKey) *ECDSA_SHA_VerifyingKeyV1 {
return &ECDSA_SHA_VerifyingKeyV1{
Curve: NamedEllipticCurve_PRIME256_V1.Enum(),
EcPublic: elliptic.Marshal(k.Curve, k.X, k.Y),
}
}
示例15: pubkeyDump
func pubkeyDump(w indent.Writer, cert *x509.Certificate) {
switch cert.PublicKeyAlgorithm {
case x509.ECDSA:
w.Printf("Public Key Algorithm: %s\n", w.Bold("ECDSA"))
pub, ok := cert.PublicKey.(*ecdsa.PublicKey)
if !ok {
w.Println(w.Bold("[unrecognizable]"))
return
}
w.Headerf("Public Key: (%s)\n", w.Bold("%d bits", pub.Params().BitSize))
w.PrintHex(elliptic.Marshal(pub.Curve, pub.X, pub.Y))
w.Dedent()
w.Printf("Curve: %s\n", EcdsaCurveName[pub.Curve])
return
case x509.RSA:
w.Printf("Public Key Algorithm: RSA\n")
case x509.DSA:
w.Printf("Public Key Algorithm: DSA\n")
default:
w.Printf("Public Key Algorithm: Unknown (type %d)\n", cert.PublicKeyAlgorithm)
}
b, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
w.Headerf("Public Key:\n")
if err != nil {
w.Printf("[unrecognizable]\n")
} else {
w.PrintHex(b)
}
w.Dedent()
}