Encrypt ini files

Asked

Viewed 626 times

3

I need a script that Compile a .ini to avoid an easy read. The file should be read with PHP. It seems that C# has a similar feature. The question is how do I do it and then read the .ini with PHP.

File example .ini:

[db_production]
host = db_production.fiber01.intraservers
type = mssql
user = db_user
pass = db_pass
namedb = db_name

2 answers

0


If this answer is not good enough, please check my other answer to this question, rather than being negative about the answer that served the author of the question and that may serve other people in the future.

You can encode your result in Base64. Stay like this:

W2RiX3Byb2R1Y3Rpb25dDQpob3N0ID0gZGJfcHJvZHVjdGlvbi5maWJlcjAxLmludHJhc2VydmVycw0KdHlwZSA9IG1zc3FsDQp1c2VyID0gZGJfdXNlcg0KcGFzcyA9IGRiX3Bhc3MNCm5hbWVkYiA9IGRiX25hbWU=

Coding Base64 in C#:

public static string Base64Encode(string plainText) {
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}

Decoding in C#:

public static string Base64Decode(string base64EncodedData) {
    var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
    return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Coding Base64 in PHP:

$codificada = base64_encode($string);

Decoding in PHP:

$original = base64_decode($codificada);
  • Exactly that, thank you very much!!

  • 1

    I always found this db password display ugly. Mts is sometimes configured in an xml, an ini a plain text file. It is an interesting doubt.

  • 7

    @Hiagosouza The problem is that Base64 is not a de facto encryption and there are even websites to untangle a coded text: https://www.base64decode.org/ (and just looking at the coded text it is already obvious that it is Base64). If you really want to stop reading, use real encryption, like a Triplede. C#: http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledes(v=vs.110).aspx. PHP: http://php.net/manual/en/mcrypt.examples.php.

  • Yes more from this I can modify the string and generate a class itself you understand? if I put a comma somewhere the return will no longer be the same.

  • 3

    @Hiagosouza If you put a comma, I shoot because I know it is not part of a Base64 representation :-) But I understood your point - in the end you will end up doing an encryption in the hand; only it will give you some work and possibly still no security. It is easier and safer to use Tripledes.

  • 3

    this is shameless, better to be without this encryption, what is the reason for this?

  • @Caffé my only concern was of an easy visualization of the password understands, I try to hinder the access to this information only that.

  • @Édipocostarebouças me sorry more at no time I spoke in safety I said I wanted to hinder the reading.

  • 1

    is that if someone is malicious and has access to your server, it is not base 64 that will prevent it. You’re making it difficult to read this iní for security, there’s no other reason for this. I understand that the answer answered your question, but as a professional I have to say that this and nothing is the same thing.

  • @Édipocostarebouças ok thanks, I appreciate the help of all. It is always good to question aggregate more knowledge and experience.

  • 2

    @Editions Rebook There is a difference between protecting a "password" and protecting a "secret" - as in the case the "password" is not that which unlocks the access to the application itself, but rather that unlocks the access to something else (the BD) the form of protection has to be different. In this case, it is very difficult to give adequate protection at a reasonable cost (that does not involve, for example, keeping the secret in memory and entering again every time you boot), so the usual is to save without protection even. Base64 when used for this purpose helps prevent access accidental, and not malicious access.

Show 6 more comments

0

Considering that my first response was much questioned, I am putting here another way to encrypt the contents of the file . ini used the algorithm TripleDES.

The method TripleDES requires an encryption key (or a salt, common name) that must be saved somewhere. For examples, suppose a Helper called SettingsReader who reads this value from somewhere.

Note that the TripleDES also uses Base64 in the algorithm.

Coding TripleDES in C#:

public static string Encrypt(string toEncrypt, bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();

    // Obtendo a chave de segurança do arquivo de configuração.

    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                     typeof(String));
    //System.Windows.Forms.MessageBox.Show(key);
    //If hashing use get hashcode regards to your key
    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        hashmd5.Clear();
    }
    else
        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    tdes.Key = keyArray;

    // Há 5 modos de operação. O utilizado nessa resposta é o ECB (Electronic Code Book)
    tdes.Mode = CipherMode.ECB;
    // O padding é o método definido para trabalhar com bytes residuais.
    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateEncryptor();
    byte[] resultArray = 
      cTransform.TransformFinalBlock(toEncryptArray, 0, 
      toEncryptArray.Length);
    tdes.Clear();

    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

Decoding TripleDES in C#:

public static string Decrypt(string cipherString, bool useHashing)
{
    byte[] keyArray;    
    byte[] toEncryptArray = Convert.FromBase64String(cipherString);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                 typeof(String));

    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        hashmd5.Clear();
    }
    else
    {
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    tdes.Key = keyArray;

    tdes.Mode = CipherMode.ECB;
    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(
                         toEncryptArray, 0, toEncryptArray.Length);           
    tdes.Clear();
    return UTF8Encoding.UTF8.GetString(resultArray);
}

Coding TripleDES in PHP:

function encrypt($input,$ky)
{
   $key = $ky;
   $size = mcrypt_get_block_size(MCRYPT_TRIPLEDES, 'ecb');
   $input = pkcs5_pad($input, $size);
   $td = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'ecb', '');
   $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
   mcrypt_generic_init($td, $key, $iv);
   $data = mcrypt_generic($td, $input);
   mcrypt_generic_deinit($td);
   mcrypt_module_close($td);
   $data = base64_encode($data);
   $data = urlencode($data);
   return $data;
}

Decoding TripleDES in PHP:

function decrypt($crypt,$ky)
{

    $crypt = urldecode($crypt);
    $crypt = base64_decode($crypt);
    $key = $ky;
    $td = mcrypt_module_open (MCRYPT_TRIPLEDES, '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $decrypted_data = mdecrypt_generic ($td, $crypt);
    mcrypt_generic_deinit ($td);
    mcrypt_module_close ($td);
    $decrypted_data = pkcs5_unpad($decrypted_data);
    $decrypted_data = rtrim($decrypted_data);
    return $decrypted_data;
}

Additional functions to take care of the padding:

function pkcs5_pad($text, $blocksize)
{
   $pad = $blocksize - (strlen($text) % $blocksize);
   return $text . str_repeat(chr($pad), $pad);
}

function pkcs5_unpad($text)
{
   $pad = ord($text{strlen($text)-1});
   if ($pad > strlen($text)) return false;
   return substr($text, 0, -1 * $pad);
}
  • 2

    really not much miracle, continues 6 by half dozen. but I do not believe that the problem is the answer, but yes the question.

  • 1

    Your first answer is perfect, the people you’re criticizing don’t know what you’re talking about. Using symmetric encryption to protect passwords and using nothing is pretty much the same thing. And if a hash does not apply (because the original password is indispensable to the operation of the application), trying to add "protection" will only give an illusion of security, not true security.

  • @mgibsonbr I thank you immensely for your lucidity ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.