Forum OpenACS Q&A: Re: example: using openssl to encrypt/decrypt cc information

Same functions, but now they also translate the binary into base64 making it possible to both eliminate the temporary file nonsense and making it easier to stuff these things into the database.
ad_proc cc_encrypt {
    passphrase  crypto  cc_number  cc_name  cc_type
    cc_exp_month  cc_exp_year  cc_address
    cc_city  cc_state  cc_zip
} {
    Encrypts the cc information according to various crypto parameters
    and crypto schemes.  Plaintext (nothing) and openssl bf

} {
    set plaintext "${cc_number}__:__${cc_name}__:__${cc_type}__:__${cc_exp_month}__:__${cc_exp_year}__:__${cc_address}__:__${cc_city}__:__${cc_state}__:__${cc_zip}"

    switch $crypto {
        plaintext -
        default {
            # plaintext noop
            return $plaintext
        }
        openssl-bf {
            set crypt [exec echo $plaintext | openssl bf -pass pass:${passphrase} | openssl base64]
            return $crypt
        }
    }
}

ad_proc cc_decrypt {
    passphrase
    crypto
    encrypted_string
} {
    Decrypts the cc information according to various crypto parameters
    and crypto schemes.  Currently implements plaintext and openssl-bf

} {
    switch $crypto {
        plaintext -
        default {
            # plaintext noop
            set decrypted_string $encrypted_string
        }
        openssl-bf {
            set decrypted_string [exec echo $encrypted_string | openssl base64 -d | openssl bf -pass pass:${passphrase} -d] 
        }
    }

    if {[regexp {^(.*)__:__(.*)__:__(.*)__:__(.*)__:__(.*)__:__(.*)__:__(.*)__:__(.*)__:__(.*)$} $decrypted_string match cc_number cc_name cc_type cc_exp_month cc_exp_year cc_address cc_city cc_state cc_zip]} {
        return [list cc_number $cc_number cc_name $cc_name cc_type $cc_type cc_exp_month $cc_exp_month cc_exp_year $cc_exp_year cc_address $cc_address cc_city $cc_city cc_state $cc_state cc_zip $cc_zip]
    } else {
        return [list error error]
    }
}

The only drawback of this approach is that if you have a doublequote character, the "echo" command will get confused. I really would prefer to have something like "ns_encrypt" working but I'll need to get deeper into it.