4

SO I am using the R PKI package, thanks to Simon Urbanek, and am trying to understand the application of signing a message. So I can figure out 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 later be reconstructed via

  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 verified again as

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

However, sig is raw

str(sig)

and when it is written to a file you get

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

but you can no longer verify the signature as it is now a string and not raw and charToRaw does not recreate the original signature. I can get part of the way there but not to get a correctly formatted raw vector to verify the signature

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

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

1 Answers1

0

Not sure this is the most direct answer to the question but it does allow for a text sting that can be written to file and then reformatted.

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