DEV Community

Cover image for Simple encryption for hiding passwords
Pavel Polívka
Pavel Polívka

Posted on

2

Simple encryption for hiding passwords

Recently I needed to pass JSON between Simple Java Script app and piece of Python code used in TeamCity build configuration. That JSON was containing passwords and TeamCity was unfortunately showing it in UI.

I tried playing with Team City password hiding features, but those are fairly limited and not able to be passed between builds in the chain.

I implemented a very simple encryption on both sides (JS and Python) and I am encrypting the password in JSON. This way Team City shows only the encrypted password, I can have all the passwords I need in my JSON.

I choose XOR cipher as my encryption method. I could not add any crypto libraries into my Python code and XOR is super easy to implement in both languages. I base64 encode the result of the encryption to make it nicer string.

Here is my implementation for JS

function encode(key, data) {
    return btoa(xorEncrypt(key, data));
}

function xorEncrypt(key, data) {
    return _.map(data, function(c, i) {
        return c.charCodeAt(0) ^ keyCharAt(key, i);
    });
}

function keyCharAt(key, i) {
    return key.charCodeAt( Math.floor(i % key.length) );
}

I use undescore.js here.

Here is my implementation for Python

import base64
import math


def key_char_at(key, i):
    return key[math.floor(i % len(key))]

def decode(key, password):
    base64_bytes = password.encode('ascii')
    password_bytes = base64.b64decode(base64_bytes)
    decodedPassword = password_bytes.decode('ascii')
    password_array = decodedPassword.split(",")
    finalPassword = []
    for i in range(len(password_array)):
        finalPassword.append(chr(int(password_array[i]) ^ ord(key_char_at(key, i))))
    return ''.join(finalPassword)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more