HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Encrypt message for sending over non secure network

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
securenonmessagesendingnetworkforencryptover

Problem

wRecently needed to swap keys with a colleague on the other side of the country.

This script encrypts a file using the other persons public key that is stored on github. It outputs a script that will re-generate the original message (if you have the private key).

```
#!/bin/bash
#
# Usage:
# ./crypt
#
# 1) Github User
# 2) File to be encrypted

#
# Requires:
# On the creators end:
# curl
# python
# python pyasn1 (sudo easy_install pyasn1)
# base64
# openssl
#
# On the receivers end
# base64
# openssl

#
# Get the users public Key
curl -s -o /tmp/ssh.pub https://github.com/${1}.keys

#
# ssh-keygen -f /tmp/ssh.pub -e -m PKCS8 # > /tmp/pem.pub
#
# The following is required because ssh-keygen -m PKCS8 has
# been removed from the Mac. The following python script
# performs the same operation.
#
python - /tmp/pem.pub

import sys, base64, struct
from pyasn1.type import univ
from pyasn1.codec.der import encoder as der_encoder

keydata = base64.b64decode(
open("/tmp/ssh.pub").readlines()[0].split()[1])

parts = []
while keydata:
dlen = struct.unpack('>I', keydata[:4])[0]
data, keydata = keydata[4:dlen+4], keydata[4+dlen:]
parts.append(data)

e_val = long(parts[1].encode('hex'), 16)
n_val = long(parts[2].encode('hex'), 16)

pkcs1_seq = univ.Sequence()
pkcs1_seq.setComponentByPosition(0, univ.Integer(n_val))
pkcs1_seq.setComponentByPosition(1, univ.Integer(e_val))
pkcs1_val = der_encoder.encode(pkcs1_seq)

head_seq = univ.Sequence()
head_seq.setComponentByPosition(0, univ.ObjectIdentifier('1.2.840.113549.1.1.1'))
head_seq.setComponentByPosition(1, univ.Null(''))

out_seq = univ.Sequence()
out_seq.setComponentByPosition(0, head_seq)
out_seq.setComponentByPosition(1, univ.BitString("'%s'H" % pkcs1_val.encode('hex')))

print '-----BEGIN PUBLIC KEY-----'
print base64.encodestring(der_encoder.encode(out_seq)).strip()
print '-----END PUBLIC KEY-----'
CREATEPEM

#
# Echo out the script
# That can be used to get t

Solution

-
Hardcoding /tmp/ssh.pub in doesn't look right. Makes the script vulnerable to all kinds of failures and race conditions. tempfile, perhaps?

-
Similar concern applies to /tmp/pem.pub. Strongly recommend to derive pem name from $1.

-
I am not sure I understand the significance of '1.2.840.113549.1.1.1'.

-
Is there a reason to have a bash/python mixture (vs pure python)?

Context

StackExchange Code Review Q#111268, answer score: 2

Revisions (0)

No revisions yet.