How to write secret object fetched from Goclient for kubernetes - go

I have
func (ss *K8sService) GetSecret(k8sclient kubernetes.Interface, namespace, secretName string) (secret *corev1.Secret, err error) {
secret, err = k8sclient.CoreV1().Secrets(namespace).Get(context.TODO(), secretName, metav1.GetOptions{})
return secret, err
}
Now I need to write secret object to a file.
I use file.StoreOutputinFile but I see O/P like
[91 66 108 117 101 10
In the file when I do
storeOutput("./"+utils.FolderDir+"/storage-secret.log", sec.Data["slclient.toml"])

Related

Convert zipped []byte to unzip []byte golang code

I have []byte of zip file. I have to unzip it without creating a new file, and get a []byte of that unzipped file. Please help me to do that.
I am making an API call and the response I get is the []byte in zipped format - I am trying to unzip it - and use it's content for creating a new zip file. So unzip - rezip.
Language: Golang
Code I've used:
func UnzipBytes(zippedBytes []byte) ([]byte, error) {
reader := bytes.NewReader(zippedBytes)
zipReader, err := zlib.NewReader(reader)
if err != nil {
return nil, err
}
defer zipReader.Close()
p, err := ioutil.ReadAll(zipReader)
if err != nil {
return nil, err
}
return p, nil
}
I get an error saying "zlib: invalid header"
The code that was initially used to zip the []byte
buffer := new(bytes.Buffer)
zipWriter := zip.NewWriter(buffer)
zipFile, err := zipWriter.Create(file.name)
_, err = zipFile.Write(file.content)
Hex dump of the []byte - the zippedBytes
00059350 78 b4 5b 0d 2b 81 c2 87 35 76 1b 11 4a ec 07 d1 |x.[.+...5v..J...|
00059360 76 77 a2 e1 3b d9 12 e2 51 d4 c5 bd 4b 2f 09 da |vw..;...Q...K/..|
00059370 f7 21 c7 26 73 1f 8e da f0 ff a3 52 f6 e2 00 e6 |.!.&s......R....|
You used zip.Writer to compress the data. You must close it by calling its Writer.Close() method. And you must use zip.Reader to read it, and use Reader.Open() with the same name you used when compressed it (file.name).
This is how it could look like:
func UnzipBytes(name string, zippedBytes []byte) ([]byte, error) {
reader := bytes.NewReader(zippedBytes)
zipReader, err := zip.NewReader(reader, int64(len(zippedBytes)))
if err != nil {
return nil, err
}
f, err := zipReader.Open(name)
if err != nil {
panic(err)
}
p, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return p, nil
}
Testing it:
filename := "test.txt"
filecontent := []byte("line1\nline2")
buffer := new(bytes.Buffer)
zipWriter := zip.NewWriter(buffer)
zipFile, err := zipWriter.Create(filename)
if err != nil {
panic(err)
}
if _, err = zipFile.Write(filecontent); err != nil {
panic(err)
}
if err = zipWriter.Close(); err != nil {
panic(err)
}
decoded, err := UnzipBytes(filename, buffer.Bytes())
fmt.Println(err)
fmt.Println(string(decoded))
This will output (try it on the Go Playground):
<nil>
line1
line2
If you don't know the name when decompressing, you may see all files in the Reader.Files header field. You may choose to open the first file:
func UnzipBytes(zippedBytes []byte) ([]byte, error) {
reader := bytes.NewReader(zippedBytes)
zipReader, err := zip.NewReader(reader, int64(len(zippedBytes)))
if err != nil {
return nil, err
}
if len(zipReader.File) == 0 {
return nil, nil // No file to open / extract
}
f, err := zipReader.File[0].Open()
if err != nil {
panic(err)
}
p, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return p, nil
}
This outputs the same. Try this one on the Go Playground.

Secp256k1 Public key generated with Azure Key Vault is of 43 characters

I am using Azure key vault for a pet project and I am creating Secp256k1 key pair. Steps to create the key in Azure:
Open your Key Vault resource
Choose Keys from the left side panel.
Click Generate/Import from the top left corner.
Chose Key Type: EC, EC name: P-256K (Secp256k1 basically)
Click Create.
Once I try to access the Public part of the key from my Go-lang app using below code:
func main(){
authorizer, err := kvauth.NewAuthorizerFromEnvironment()
if err != nil {
fmt.Printf("unable to create vault authorizer: %v\n", err)
os.Exit(1)
}
basicClient := keyvault.New()
basicClient.Authorizer = authorizer
getKey(basicClient, KeyName)
}
func getKey(basicClient keyvault.BaseClient, keyname string) {
keyResp, err := basicClient.GetKey(context.Background(), "https://"+vaultName+".vault.azure.net", keyname, "")
if err != nil {
fmt.Printf("unable to get value for key: %v\n", err)
os.Exit(1)
}
fmt.Println("X = ",*keyResp.Key.X)
fmt.Println("Y = ",*keyResp.Key.Y)
}
You can look at the different attributes of the Key listed here at Mircosoft Docs.
https://learn.microsoft.com/en-us/rest/api/keyvault/create-key/create-key#request-body
Above code gives me an output as:
X = uAv6rXZedQbihGUQwFkEZl35LeI7OHdhHSOEf3VpXyw
Y = Q8MzSQGOtqT41lsYU-P82o6Fryn8Vnub0l0kdOOdOHI
The given keys are 43 chars in length, while I understand by reading about Secp256k1 that these are 32 chars only. The key size being 43 is giving me an error in the application I intend to use it at.
Am I missing something here or Azure gives some extra characters or something like that?
Any help appreciated.

Send ISO8583 Message Golang

I'm trying to build a ISO8583 Client using a Golang,
when using java, i don't have any problem when creating client.
But when trying creating a client using golang (i'm just starting learning golang btw), i can't send a message to the server. Can someone help me, why i can't send a message?
I've tried to send a SIGN IN Message, The client and server already connected, but the message i send not readable by the server.
This My Code
package main
import (
"bufio"
"fmt"
"net"
"os"
"time"
"github.com/ideazxy/iso8583"
)
type ISOSignIn struct {
Bit3 *iso8583.Numeric `field:"3" length:"6" encode:"bcd"`
Bit7 *iso8583.Numeric `field:"7" length:"10" encode:"ascii`
Bit11 *iso8583.Numeric `field:"11" length:"6" encode:"rbcd`
Bit32 *iso8583.Llnumeric `field:"32" length:"11" encode:"ascii`
Bit70 *iso8583.Numeric `field:"70" length:"3" encode:"ascii`
}
func main() {
testIso()
}
func testIso() {
data := ISOSignIn{
Bit3: iso8583.NewNumeric("001111"),
Bit7: iso8583.NewNumeric("0913110004"),
Bit11: iso8583.NewNumeric("000001"),
Bit32: iso8583.NewLlnumeric("9999"), // Client ID
Bit70: iso8583.NewNumeric("301"), // Login Code
}
msg := iso8583.NewMessage("0800", data)
msg.MtiEncode = iso8583.BCD
b, err := msg.Bytes()
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("% x\n", b)
tcpClientNew(b)
}
func tcpClientNew(b []byte) {
tcpAddr, err := net.ResolveTCPAddr("tcp", "192.168.100.5:12346")
if err != nil {
println("ResolveTCPAddr failed:", err.Error())
os.Exit(1)
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
println("Dial failed:", err.Error())
os.Exit(1)
}
timeoutDuration := 30 * time.Second
_, err = conn.Write(b)
if err != nil {
println("Write to server failed:", err.Error())
os.Exit(1)
}
conn.SetReadDeadline(time.Now().Add(timeoutDuration))
bufReader := bufio.NewReader(conn)
resp, _ := bufReader.ReadByte()
fmt.Print("Message from server: " + string(resp))
conn.Close()
}
Server Already Connected
<log realm="Server-A.server.session/192.168.100.1:32218" at="Mon Jan 07 09:37:15.747 WIB 2019">
<session-start/>
</log>
<log realm="channel/192.168.100.1:32218" at="Mon Jan 07 09:37:19.034 WIB 2019" lifespan="3287ms">
<receive>
<peer-disconnect/>
</receive>
</log>
<log realm="Server-A.server.session/192.168.100.1:32218" at="Mon Jan 07 09:37:19.035 WIB 2019">
<session-end/>
</log>
Output from Client Terminal :
GOROOT=/Users/ivanaribanilia/Applications/go
GOPATH=/Users/ivanaribanilia/Project/Workspace-Github/Project-Go/pclient
/Users/ivanaribanilia/Applications/go/bin/go build -i -o /Users/ivanaribanilia/Project/Workspace-Github/Project-Go/pclient/build/pclient /Users/ivanaribanilia/Project/Workspace-Github/Project-Go/pclient/src/github.com/ivanj4u/pclient/main.go
/Users/ivanaribanilia/Project/Workspace-Github/Project-Go/pclient/build/pclient
08 00 22 20 00 01 00 00 00 00 00 11 11 30 39 31 33 31 31 30 30 30 34 30 30 30 30 30 31 30 34 31 31 31 34
Message from server:
Process finished with exit code 0
I expect a response from the server, so i can develop other message like INQUIRY or PAYMENT.
Thank you
ReadByte reads and returns a single byte. If no byte is available,
returns an error.
seems that what you read from server is only one byte, which is a white-space char.
The server and client should make a protocol when to close the connection. Thus, if server don't close the conn actively, client should read all bytes from server and close the connection. Like this:
recvBuf := make([]byte, 1024)
n, err := bufReader.Read(recvBuf)
for err == nil {
println("Recv data from server:", string(recvBuf[:n]))
n, err = bufReader.Read(recvBuf)
}
if err != io.EOF {
println("recv from server failed, err:", err)
}
conn.Close()
Or if the protocol defines the client should close the connection when received a certain byte, client can use ReadBytes() and close the connection actively.
func (b *Reader) ReadBytes(delim byte) ([]byte, error)
ReadBytes reads until the first occurrence of delim in the input,
returning a slice containing the data up to and including the
delimiter. If ReadBytes encounters an error before finding a
delimiter, it returns the data read before the error and the error
itself (often io.EOF). ReadBytes returns err != nil if and only if the
returned data does not end in delim.

Convert Redigo Pipeline result to strings

I managed to Pipeline multiple HGETALL commands, but I can't manage to convert them to strings.
My sample code is this:
// Initialize Redis (Redigo) client on port 6379
// and default address 127.0.0.1/localhost
client, err := redis.Dial("tcp", ":6379")
if err != nil {
panic(err)
}
defer client.Close()
// Initialize Pipeline
client.Send("MULTI")
// Send writes the command to the connection's output buffer
client.Send("HGETALL", "post:1") // Where "post:1" contains " title 'hi' "
client.Send("HGETALL", "post:2") // Where "post:1" contains " title 'hello' "
// Execute the Pipeline
pipe_prox, err := client.Do("EXEC")
if err != nil {
panic(err)
}
log.Println(pipe_prox)
It is fine as long as you're comfortable showing non-string results.. What I'm getting is this:
[[[116 105 116 108 101] [104 105]] [[116 105 116 108 101] [104 101 108 108 111]]]
But what I need is:
"title" "hi" "title" "hello"
I've tried the following and other combinations as well:
result, _ := redis.Strings(pipe_prox, err)
log.Println(pipe_prox)
But all I get is: []
I should note that it works with multiple HGET key value commands, but that's not what I need.
What am I doing wrong? How should I do it to convert the "numerical map" to strings?
Thanks for any help
Each HGETALL returns it's own series of values, which need to be converted to strings, and the pipeline is returning a series of those. Use the generic redis.Values to break down this outer structure first then you can parse the inner slices.
// Execute the Pipeline
pipe_prox, err := redis.Values(client.Do("EXEC"))
if err != nil {
panic(err)
}
for _, v := range pipe_prox {
s, err := redis.Strings(v, nil)
if err != nil {
fmt.Println("Not a bulk strings repsonse", err)
}
fmt.Println(s)
}
prints:
[title hi]
[title hello]
you can do it like this:
pipe_prox, err := redis.Values(client.Do("EXEC"))
for _, v := range pipe_prox.([]interface{}) {
fmt.Println(v)
}

openpgp and golang

I have some problems with the documentation.
Here is my program:
package main
import (
"bytes"
"code.google.com/p/go.crypto/openpgp"
"encoding/base64"
"fmt"
)
func main() {
var entity *openpgp.Entity
entity, err := openpgp.NewEntity("bussiere", "test", "bussiere#gmail.com", nil)
if err != nil {
}
var (
buffer bytes.Buffer
)
entity.SerializePrivate(&buffer, nil)
data := base64.StdEncoding.EncodeToString([]byte(buffer.String()))
fmt.Printf("%q\n", data)
entity.Serialize(&buffer)
data2 := base64.StdEncoding.EncodeToString([]byte(buffer.String()))
fmt.Printf("%q\n", data2)
entity.PrivateKey.Serialize(&buffer)
data3 := base64.StdEncoding.EncodeToString([]byte(buffer.String()))
fmt.Printf("%q\n", data3)
entity.PrimaryKey.Serialize(&buffer)
data4 := base64.StdEncoding.EncodeToString([]byte(buffer.String()))
fmt.Printf("%q\n", data4)
//fmt.Printf(buffer.String())
}
Here are the data:
https://gist.github.com/bussiere/5159890
here is the code on gist:
https://gist.github.com/bussiere/5159897
What is the public key?
And how to use it?
And how to make bigger key?
UPDATE: This issue has been fixed: see here
Son the solution/description below is no longer appropriate.
---------------- legacy answer starts below --------------------
Concering your question of How to build keys of an other size: it's impossible.
I ran into the exact same Problem, look at: the source code for the NewEntityFunction:
383 const defaultRSAKeyBits = 2048
384
385 // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
386 // single identity composed of the given full name, comment and email, any of
387 // which may be empty but must not contain any of "()<>\x00".
388 // If config is nil, sensible defaults will be used.
389 func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
390 currentTime := config.Now()
391
392 uid := packet.NewUserId(name, comment, email)
393 if uid == nil {
394 return nil, errors.InvalidArgumentError("user id field contained invalid characters")
395 }
396 signingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
397 if err != nil {
398 return nil, err
399 }
400 encryptingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
401 if err != nil {
402 return nil, err
403 }
defaultRSAKeyBits is a pkg-level unexported constant. So no chance of modifing this beheavior.
I ended up copying the whole function out, adding a parameter for the keybits and keeping it in my codebase,
if someone has a better solution, I'd be glad to hear it.

Resources