R RSA signature raw for character and back

SO I am using the PKI R package, thanks to Simon Urbanek, and trying to understand the use of message signatures. Therefore, I can understand how to sign something.

    require(PKI)

# generate 2048-bit RSA key
key <- PKI.genRSAkey(bits = 2048L)

# extract private and public parts as PEM
priv.pem <- PKI.save.key(key)
pub.pem <- PKI.save.key(key, private=FALSE)
# load back the public key separately
pub.k <- PKI.load.key(pub.pem)

# encrypt with the public key
x <- PKI.encrypt(charToRaw("Hello, world!"), pub.k)
# decrypt with private key
rawToChar(PKI.decrypt(x, key))

# So straight from the Package examples I have the public and private keys.

# Additionally, with the same I can sign a message
x <- charToRaw("My message to sign")
sig <- PKI.sign(x, key)
PKI.verify(x, sig, key)

# Now a slight change from the exapmles I will verify that the public key can verify
PKI.verify(x, sig, pub.k)

pub.pem can be written to a file as

PuK<-paste(pub.pem, collapse="")

and can be later remodeled through

  pub.pem<-substring(PuK, 
               c(1, 27, 91, 155, 219, 283, 347, 411, 419), 
               c(26, 90,154,218,282,346,410,418,442))
  pub.k <- PKI.load.key(pub.pem)

and then checked again as

PKI.verify(x, sig, pub.k)

However sig is raw

str(sig)

and when it is written to the file, you get

sig<-paste(sig, collapse=" " )

but you can no longer verify the signature, since it is now a string, not raw, and charToRaw does not recreate the original signature. I can get part of the path there, but not get a correctly formatted raw vector for signature verification

sigraw<-rawToChar(sig2, multiple = TRUE)
str(sapply(sigraw, FUN=charToRaw))

So, is there a way to write the signature to a file and then come back again to verify the signature?

+4
1

, , , , .

library("BMS")
library("PKI")
library("pack")

# generate 2048-bit RSA key
key <- PKI.genRSAkey(bits = 2048L)
# extract private and public parts as PEM
priv.pem <- PKI.save.key(key)
pub.pem <- PKI.save.key(key, private=FALSE)
# load back the public key separately
pub.k <- PKI.load.key(pub.pem)
x <- charToRaw("My message to sign")
sig <- PKI.sign(x, key)
PKI.verify(x, sig, key)

bits<-rawToBits(sig)

###  This part can be skipped, long way to make character vector & back  ###
pbitsb<-paste(bits)
back<-sapply(pbitsb, FUN=as.raw)
back==bits
sigbits<-packBits(bits, type="raw")
sigback<-packBits(back, type="raw")
sig==sigbits&sigbits==sigback
PKI.verify(x,sigback,key)


#Can make this more compressed character vector
hexsig<-bin2hex(as.numeric(bits))

#This is the value to be shared in a text file as proof of signature


#The remaineder needs to be executed by the recipient
binsig<-hex2bin(hexsig)

backbin<-sapply(binsig, FUN=as.raw)
sigbin<-packBits(backbin, type="raw")
PKI.verify(x,sigbin,key)


sig==sigbits&sigbits==sigback&sigback==sigbin
0

Source: https://habr.com/ru/post/1585009/


All Articles