Exemplo n.º 1
0
 def encrypt(self, data, cipher=None):
     if not cipher:
         cipher = self.defaultcipher
     nonce = genkey(str(random.getrandbits(512)))[:32].strip()
     enckey = genkey(self.secret, nonce)[:32].strip()
     params = ["enc", "-e", "-a", "-%s" % cipher,
               "-pass", "stdin"]
     retval, res = self.run(params, output=data, passphrase=enckey)
     ret = "%s\ncipher: %s\nnonce: %s\n\n%s\n%s" % (
         self.beginblock, cipher, nonce, res["stdout"], self.endblock)
     return ret
Exemplo n.º 2
0
    def decrypt(self, data):
        try:
            head, enc, tail = data.split("\n\n")
            head = [h.strip() for h in head.split("\n")]
        except:
            try:
                head, enc, tail = data.split("\r\n\r\n")
                head = [h.strip() for h in head.split("\r\n")]
            except:
                raise ValueError("Not a valid OpenSSL encrypted block.")

        if (not head or not enc or not tail
                or head[0] != self.beginblock
                or tail.strip() != self.endblock):
            raise ValueError("Not a valid OpenSSL encrypted block.")

        try:
            headers = dict([l.split(': ', 1) for l in head[1:]])
        except:
            raise ValueError("Message contained invalid parameter.")

        cipher = headers.get('cipher', self.defaultcipher)
        nonce = headers.get('nonce')
        if not nonce:
            raise ValueError("Encryption nonce not known.")

        enckey = genkey(self.secret, nonce)[:32].strip()
        params = ["enc", "-d", "-a", "-%s" % cipher,
                  "-pass", "stdin"]
        retval, res = self.run(params, output=enc, passphrase=enckey)
        return res["stdout"]