How to hidden Umbral Key - encryption

As umbral-doc define
Main operation of Umbral KEM
Alice use public Key encapsulaition, the K (key used for chacha20 encrypt) was genrated.
ReEncryption for shared to bob.
Final, Bob use privateKey get K and cipherText, decrypt cipherText get plainText.
My Question is:
Final, Bob get decrypt Key, so next time Bob can use decrypt Key decrypt cipherText without gather cFrags, also can send key to other(like clark), How to keep the secret.
The umbral program guide like:
from umbral import pre, keys, signing
# Generate Umbral keys for Alice.
alices_private_key = keys.UmbralPrivateKey.gen_key()
alices_public_key = alices_private_key.get_pubkey()
alices_signing_key = keys.UmbralPrivateKey.gen_key()
alices_verifying_key = alices_signing_key.get_pubkey()
alices_signer = signing.Signer(private_key=alices_signing_key)
# Generate Umbral keys for Bob.
bobs_private_key = keys.UmbralPrivateKey.gen_key()
bobs_public_key = bobs_private_key.get_pubkey()
# Generate Umbral keys for Clark.
clarks_private_key = keys.UmbralPrivateKey.gen_key()
clarks_public_key = clarks_private_key.get_pubkey()
# Encrypt data with Alice's public key.
plaintext = b'Proxy Re-Encryption is cool!'
ciphertext, capsule = pre.encrypt(alices_public_key, plaintext)
# Decrypt data with Alice's private key.
cleartext = pre.decrypt(ciphertext=ciphertext,
capsule=capsule,
decrypting_key=alices_private_key)
# Alice generates "M of N" re-encryption key fragments (or "KFrags") for Bob.
# In this example, 10 out of 20.
kfrags = pre.generate_kfrags(delegating_privkey=alices_private_key,
signer=alices_signer,
receiving_pubkey=bobs_public_key,
threshold=10,
N=20)
capsule.set_correctness_keys(delegating=alices_public_key,
receiving=bobs_public_key,
verifying=alices_verifying_key)
cfrags = list() # Bob's cfrag collection
for kfrag in kfrags[:10]:
cfrag = pre.reencrypt(kfrag=kfrag, capsule=capsule)
cfrags.append(cfrag) # Bob collects a cfrag
for cfrag in cfrags:
capsule.attach_cfrag(cfrag)
bob_cleartext = pre.decrypt(ciphertext=ciphertext,
capsule=capsule,
decrypting_key=bobs_private_key)
assert bob_cleartext == plaintext
print(bob_cleartext)

Related

3DES Decryption Returning Encrypted Characters at End of Decrypted Password

I'm having a problem with password decryption that has worked correctly for some 10 years in a VB6 DLL but now on newer, faster servers, it's returning the last few encrypted characters of the stored password. For example, "1234" is stored as "Žl¹è=" but when that is decrypted it's coming back with "1234 ¹è=". This code was written well before I started working with the program and I know little about encryption/decryption.
What appears to be the relevant code is shown below:
'Prepare sCryptBuffer for CryptDecrypt
lCryptBufLen = Len(sInputBuffer)
sCryptBuffer = String(lCryptBufLen, vbNullChar)
LSet sCryptBuffer = sInputBuffer
'Decrypt data: lHkey=Encryption Key, 0 = No Hash, 1=True (for final?), 0=dwFlags?, sCryptBuffer=data to be decrypted, lCryptBufLen=length of the pbData buffer
If Not CBool(CryptDecrypt(lHkey, 0, 1, 0, sCryptBuffer, lCryptBufLen)) Then
GoTo Finished
End If
'Setup output buffer with just decrypted data
strDecryptedText = Mid$(sCryptBuffer, 1, GetResultsBufferLength(sInputBuffer))
strDecryptedText = Replace(strDecryptedText, vbNullChar, "")
'If the last characters ASCII value is 8 or less, this number represents the amount
'of padding that is on the decrypted text.
If Asc(Right(strDecryptedText, 1)) <= 8 Then
DecryptEx = Left(strDecryptedText, Len(strDecryptedText) - Asc(Right(strDecryptedText, 1)))
Else
DecryptEx = strDecryptedText
End If
The GetResultsBufferLength function appears to use the following line of code for 3DES:
lngReturn = lngTempLength - ((lngTempLength + 8) Mod 8) + 8
Any ideas will be much appreciated.

The encryption won't decrypt

I was given an encrypted copy of the study guide here, but how do you decrypt and read it???
In a file called pa11.py write a method called decode(inputfile,outputfile). Decode should take two parameters - both of which are strings. The first should be the name of an encoded file (either helloworld.txt or superdupertopsecretstudyguide.txt or yet another file that I might use to test your code). The second should be the name of a file that you will use as an output file.
Your method should read in the contents of the inputfile and, using the scheme described in the hints.txt file above, decode the hidden message, writing to the outputfile as it goes (or all at once when it is done depending on what you decide to use).
The penny math lecture is here.
"""
Program: pennyMath.py
Author: CS 1510
Description: Calculates the penny math value of a string.
"""
# Get the input string
original = input("Enter a string to get its cost in penny math: ")
cost = 0
Go through each character in the input string
for char in original:
value = ord(char) #ord() gives us the encoded number!
if char>="a" and char<="z":
cost = cost+(value-96) #offset the value of ord by 96
elif char>="A" and char<="Z":
cost = cost+(value-64) #offset the value of ord by 64
print("The cost of",original,"is",cost)
Another hint: Don't forget about while loops...
Another hint: After letters -
skip ahead by their pennymath value positions + 2
After numbers - skip ahead by their number + 7 positions
After anything else - just skip ahead by 1 position
The issue I'm having in that I cant seem to get the coding right to decode the file it comes out looking the same. This is the current code I have been using. But once I try to decrypt the message it stays the same.
def pennycost(c):
if c >="a" and c <="z":
return ord(c)-96
elif c>="A" and c<="Z":
return ord(c)-64
def decryption(inputfile,outputfile):
with open(inputfile) as f:
fo = open(outputfile,"w")
count = 0
while True:
c = f.read(1)
if not c:
break;
if count > 0:
count = count -1;
continue
elif c.isalpha():
count = pennycost(c)
fo.write(c)
elif c.isdigit():
count = int(c)
fo.write(c)
else:
count = 6
fo.write(c)
fo.close()
inputfile = input("Please enter the input file name: ")
outputfile = input("Plese enter the output file name(EXISTING FILE WILL BE OVER WRITTEN!): ")
decryption(inputfile,outputfile)

Why gpg --encrypt fails with sub key packet with key flags 0x0C that never expires?

When I analyze the output of that gpg --list-packets output I see that the sub key packet never expires, and its key flags is 0C which is for "Encryption". (see output at the bottom.)
The public key packet is already expired but its key flags is 03 which stands for "Key Certification" | "Sign Data", and therefore is not needed for encryption.
Yet when I run gpg --always-trust -r user#user.com --encrypt abc I get this error:
gpg: user#user.com: skipped: unusable public key
gpg: abc: encryption failed: unusable public key
Why is this so? Why the "never expire" encryption key is not usable in this case? Is the fact that public key expired, regardless of what the key flags is, all sub keys automatically invalid?
Here is the output of gpg --list-packets user.public.key:
gpg: WARNING: using insecure memory!
gpg: please see http://www.gnupg.org/faq.html for more information
:public key packet:
version 4, algo 1, created 1471460125, expires 0
pkey[0]: [2048 bits]
pkey[1]: [17 bits]
:user ID packet: "userid <user#user.com>"
:signature packet: algo 1, keyid A5038DC251BC03DC
version 4, created 1471460130, md5len 0, sigclass 0x13
digest algo 2, begin of digest c4 fa
hashed subpkt 2 len 4 (sig created 2016-08-17)
hashed subpkt 9 len 4 (key expires after 2y0d0h0m)
hashed subpkt 27 len 1 (key flags: 03)
hashed subpkt 11 len 7 (pref-sym-algos: 2 3 4 7 8 9 10)
hashed subpkt 22 len 4 (pref-zip-algos: 2 1 0 3)
hashed subpkt 25 len 1 (primary user ID)
subpkt 16 len 8 (issuer key ID A5038DC251BC03DC)
data: [2046 bits]
:public sub key packet:
version 4, algo 1, created 1471460125, expires 0
pkey[0]: [2048 bits]
pkey[1]: [17 bits]
:signature packet: algo 1, keyid A5038DC251BC03DC
version 4, created 1471460131, md5len 0, sigclass 0x18
digest algo 2, begin of digest 7f 63
hashed subpkt 2 len 4 (sig created 2016-08-17)
hashed subpkt 27 len 1 (key flags: 0C)
subpkt 16 len 8 (issuer key ID A5038DC251BC03DC)
data: [2042 bits]
After further analysis this is what I came up to:
Instead of using gpg --list-packets I use gpg --with-colon, and I take the first pub key from the output. I have noticed that if the pub key is not expired then it always allows encryption. If pub is expired then it does not matter what sub is - the key is expired and gpg refuses to encrypt.
Example of the never expired public key with expired subkeys (using gpg --with-colon user.public.key)
pub:-:3072:1:BFDEF66008072C77:2016-08-21:::-:userid <user#user.com>:
sub:-:3072:1:1AF28CF198A6BEA3:2016-08-21:2018-08-21::: [expires: 2018-08-21]
sub:-:3072:1:DA2B5429D88156C7:2016-08-21:2016-08-26::: [expires: 2016-08-26]
This one will allow encryption.
See details how to process this output here:
https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob_plain;f=doc/DETAILS
Example of

Authenticating API in R

I'm trying to access Bitfinex via api but struggling to properly authenticate my request. There is a Python example of what I want to do (https://gist.github.com/jordanbaucke/5812039) but I can't seem to get it to work in R.
key <- c("MY API KEY")
secret = c("MY API SECRET")
req <- GET("https://api.bitfinex.com/v1/balances",
authenticate(key, secret))
add_headers(X-BFX-APIKEY = key))
stop_for_status(req)
content(req)
Can someone tell me what I'm doing wrong?
/v1/balances is a Bitfinex authenticated endpoints, thus it requires the POST request with a proper handling of payload and headers.
Here is a working example from my own script:
library(httr)
key <- "..."
secret <- "..."
# payload JSON object, the request should refer to the URL
# nonce should always be greater than for previous calls
payload_json <- list(request = '/v1/account_infos', nonce = as.character(as.numeric(as.POSIXct(Sys.time()))))
# creating string from JSON payload
payload <- jsonlite::toJSON(payload_json, auto_unbox = TRUE)
# encoding payload string
payload_str <- base64enc::base64encode(charToRaw(as.character(payload)))
# adding three Bitfinex headers:
# X-BFX-APIKEY = key
# X-BFX-PAYLOAD = base64 encoded payload string
# X-BFX-SIGNATURE = sha384 encrypted payload string with the secret key
req <- POST("https://api.bitfinex.com/v1/account_infos",
add_headers('X-BFX-APIKEY' = key,
'X-BFX-PAYLOAD' = payload_str,
'X-BFX-SIGNATURE' = openssl::sha384(payload_str, key = secret))
)
content(req)
For creating "New Order" you only need to change the payload to something, like this:
payload_json <- list(request = '/v1/account_infos',
nonce = as.character(as.numeric(as.POSIXct(Sys.time()))),
symbol = 'BTCUSD',
amount = '0.3',
price = '1000',
exchange = 'bitfinex',
side = 'sell',
type = 'exchange market'
)
The rest of the code will work without changes.
For list of payload parameters check the Bitfinex API docs, e.g. "New Order".

One-time pad solution incorrect

A one time pad encryption system represents the letters A-E with numbers 1-5 and a space with the number 0. Given the cipher text: DBCA
and the one time pad: BCBC
What is the encrypted word?
My solution:
A B C D E _
1 2 3 4 5 0
Cipher text: DBCA
One-time pad & key: BCBC
B C B C
2 3 2 3
D B C A
4 2 3 1
Encrypted text:
B A A B
2 1 1 2
The encrypted word I got is: BAAB which isn't a word so I'm so it's incorrect
I've researched how to use one-time pad but I still don't understand it
One-time pad is not like that.
your code length must be at least as long as your text. Since you are going to use it one time for each encrypting and decrypting your text.
f = open("plain.txt", "rb+")
kf = open ("key.txt", "rb" )
f2= open("cipher.txt", "r+")
allplain = f.read()
key =[]
key = kf.read()
# - encrypt plain text and save into cipher.txt
for i in range(len(allplain)):
k = chr (key[i])
p = chr (allplain[i])
c = chr ((ord(p)) ^ (ord(k)))
f2.write(c)
this is a complete implementation of One-Time Pad encryption in Python.
One-Time Pad Encryption

Resources