I am learning about encryption and using crypto-js I have made a Js & c# version.
What I am trying to accomplish is that the JS or c# version will be able to decode each other messages.
For testing I have kept the IV and KEY , paddding and mode the same in both the JS and C# instance.
I have them both decrypting and encrypting data respectivly but what I have yet to accomplish is providing an encrypted from JS be able to decode using c#.
JS
var key = CryptoJS.enc.Base64.parse('7061737323313233');
var iv = CryptoJS.enc.Base64.parse('7061737323313233');
var encrypted = CryptoJS.AES.encrypt("It works", key,
{ keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7 });
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
document.write('Encrypted :' + encrypted + '<br>');
document.write('Key :' + encrypted.key + '<br>');
document.write('Salt :' + encrypted.salt + '<br>');
document.write('iv :' + encrypted.iv + '<br>');
document.write('Decrypted : ' + decrypted + '<br>');
document.write('utf8 = ' + decrypted.toString(CryptoJS.enc.Utf8) + '<br>');
C#
public void startEncryption(string original )
{
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
//Settings
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
myRijndael.FeedbackSize = 128;
keybytes = Encoding.UTF8.GetBytes("7061737323313233");
//Should be made unique for each message!. TODO
iv = Encoding.UTF8.GetBytes("7061737323313233");
// Encrypt the string to an array of bytes.
encrypted = EncryptStringToBytes(original, keybytes, iv);
//Show Encrypted data
txt_Output.Text = Convert.ToBase64String(encrypted);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, keybytes, iv);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
Where the problem arises in decryption.
private void btn_Decrypt_Click(object sender, EventArgs e)
{
Console.WriteLine("Decrypting..");
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
//Settings
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.PKCS7;
myRijndael.FeedbackSize = 128;
keybytes = Encoding.UTF8.GetBytes("7061737323313233");
//Should be made unique for each message!. TODO
iv = Encoding.UTF8.GetBytes("7061737323313233");
// Decrypt the bytes to a string.
string roundtrip = DecryptToString(txt_Output.Text);
txt_Output.Text = roundtrip;
//Display the original data and the decrypted data.
}
}
public string DecryptToString(string TextValue)
{
return DecryptStringFromBytes(Convert.FromBase64String(TextValue), keybytes, iv);
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.Mode = CipherMode.CBC;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt =
new CryptoStream(msDecrypt,decryptor,CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
I am producing different encrypted size strings:
JS:MhAP11fHa+fUfRzSw2UHVQ==
C#:+Ijpt1GDVgM4MqMAQUwf0Q==
I get Padding is invalid and cannot be removed, when trying to decrypt the JS string in c#
Where have I got wrong?.
Basically you run into encoding issues. First of all, you parse your IV using Base64 decoding in one implementation and one using direct character encoding in the other. Your Base64 strings don't look like Base64 strings either.
Furthermore, many libraries (incorrectly) allow that incorrect key and IV sizes are used. This is however confusing as there is no generic way for key or IV expansion. So you should make sure that the binary representations of the key and IV are correct for the specific algorithm.
For AES you should use a key size of 128, 192 or 256 bits and an IV size identical to the block size, 128 bits. The IV should be randomly generated and communicated to the other side, e.g. by prefixing the IV to the ciphertext.
Related
i want to encrypt a json data
{
"urc": "7718313198",
"umc": "101871",
"ak": "asdfgh123456",
"fname": "Biswajit",
"lname": "Dolui",
"email": "retailer001#giblvirtualmail.com",
"phno": "7718313198",
"pin": "712410"
}
i could not encrypt long string in asp.net using rsa algorithm 2048
var csp = new RSACryptoServiceProvider(2048);
//how to get the private key
var privKey = csp.ExportParameters(true);
//and the public key ...
var pubKey = csp.ExportParameters(false);
//converting the public key into a string representation
string pubKeyString;
{
//we need some buffer
var sw = new System.IO.StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, pubKey);
//get the string from the stream
pubKeyString = sw.ToString();
}
//converting it back
{
//get a stream from the string
var sr = new System.IO.StringReader(pubKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
pubKey = (RSAParameters)xs.Deserialize(sr);
}
//conversion for the private key is no black magic either ... omitted
//we have a public key ... let's get a new csp and load that key
csp = new RSACryptoServiceProvider();
csp.ImportParameters(pubKey);
//we need some data to encrypt
var plainTextData = "{urc: 7718313198,umc: 101871,ak: asdfgh123456,fname: Biswajit,lname: Dolui,email: biswajitdoluicse#gmail.com,phno: 7718313198}";
//for encryption, always handle bytes...
var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);
//apply pkcs#1.5 padding and encrypt our data
var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);
//we might want a string representation of our cypher text... base64 will do
var cypherText = Convert.ToBase64String(bytesCypherText);
I'm trying to write the C# equivalent for the following Java code:
protected static final String DES_ECB_PKCS5PADDING = "DESede/ECB/PKCS5Padding";
public static String decryptValueDirect(String value, String key)
throws NoSuchAlgorithmException, NoSuchPaddingException,
GeneralSecurityException, IllegalBlockSizeException,
BadPaddingException {
byte[] bytes = Base64.decodeBase64(value);
Cipher cipher = Cipher.getInstance(DES_ECB_PKCS5PADDING);
cipher.init(Cipher.DECRYPT_MODE, convertSecretKey(key.getBytes()));
byte[] decryptedValue = cipher.doFinal(bytes);
String nstr = new String(decryptedValue);
return nstr;
}
protected static SecretKey convertSecretKey(byte[] encryptionKey) throws GeneralSecurityException {
if (encryptionKey == null || encryptionKey.length == 0)
throw new IllegalArgumentException("Encryption key must be specified");
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(TRIPLEDES);
KeySpec keySpec = new DESedeKeySpec(encryptionKey);
return keyFactory.generateSecret(keySpec);
}
The source text is a base64 encoded, then encrypted and then base64 encoded for transport on a rabbit queue. Our vendor who handles the encryption provided the above for decryption in Java, but has no idea about C#.
The only input on the encryption side is a key, a random string. We use the same string for encryption/decryption 012345678901234567890123456789 in our dev env. That is the only input, no salt, hashing (that i see) or pw iterations. The only requirement is that it is at least 24 chars long.
My C# code is below and a fiddle of my attempt is here.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
//Message Data value
//We are using encrypted multibyte.
string myData = #"ROE8oYeV7B6faUsvfIx0Xe55vSs9IR5DlWGRbSM+lmKmLcaJsA13VudwWlAEYtLUD8+nMXShky0grSxsk0Z9cQe5V45XnAIfUhnyzI9a0jtMFC8XnIZ5dbclPO/V73QnieIZDkbNV5cPo3BM+l79ai96KB/gkF3xuerFPxvWejtPyWbOyO+FfNyFps4gAYDITsYIAEH39VP4eipmQ5zc18BA39lajQ3UaVewSxz7H+x3Ooe2SzJT/TQWRkioJSEFwexqzkHiLOQ0MOCIVD9xTWpLYnsL3LMwyF6H8f0PY4Fc57LVGhvUZ7dsB9NWUAnmG3uqbsonNFVhuXyvJTWNyFOHwFzOMx6XDLJJFHGZhaHg2VrescfnpUtonQY08RgojBngyJNRqK8URAvI3bqKq8Y7F/9HmEtMIIQe6KuuTmU=";
string myKey = "012345678901234567890123456789";//Development Env Key.
Console.WriteLine("Decrypt1:");
string s = Decrypt1(myData, myKey);
Console.ReadLine();
}
public static string Decrypt1(string value, string decryptionKey)
{
string decryptString = "";
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();
try
{
byte[] decodedData = Convert.FromBase64String(value);
tDESalg.Mode = CipherMode.ECB;
tDESalg.Padding = PaddingMode.PKCS7;//According to MS, same as PKCS5PADDING
byte[] Key = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(decryptionKey));
//byte[] IV = tDESalg.IV;
byte[] IV = new byte[tDESalg.BlockSize / 8]; //The size of the IV property must be the same as the BlockSize property divided by 8
var memoryStream = new MemoryStream(decodedData);
var cryptoStream = new CryptoStream(memoryStream, tDESalg.CreateDecryptor(Key, IV), CryptoStreamMode.Read);
var reader = new StreamReader(cryptoStream);
decryptString = reader.ReadToEnd();
byte[] decryptData = Convert.FromBase64String(decryptString);
}
catch (Exception e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message + e.StackTrace);
return null;
}
return decryptString;
}
}
Searching seems to point to the same answer, the key, encoding, ... all must be the same. I just don't know what that would be the equivalent for the Java source provided. :) Any suggestions will be helpful.
MD5 has a 16-byte output, Triple DES (3DES) requires a 24-byte key. There is a key size mis-match.
The C# and Java key derivations are substantially different:
C#:
byte[] Key = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(decryptionKey));
returns 16-bytes.
Java:
SecretKeyFactory.getInstance(TRIPLEDES)
returns 24-bytes.
There is a key option (2TDEA) where a 16-byte key is used and the first 8-bytes will be duplicated to create the last 8-bytes. NIST has deprecated this option.
Some implementations will accept a 16-byte key and extend the key to 24-bytes and some will not. You should provide all 24-bytes to 3DES, do not rely on an implementation to create the 24-byte key.
Note: The question was updated so it is not clear that the the actual encrytpion key is derived.
Recently I began developing a new MVC app and needed to take an older existing asp.net membership database and convert it into the new(er) Identity system.
If you've found yourself in a similar situation, then likely you've come upon this helpful post from microsoft which gives you great guidance and scripts on converting the database over to the new schema, including the passwords.
To handle the differences in hashing/encryption of passwords between the two systems, they include a custom password hasher, SqlPasswordHasher, which parses the password field (which has been combined into Password|PasswordFormat|Salt) and attempts to duplicate the logic found inside SqlMembershipProvider to compare the incoming password with the stored version.
However, as I (and another commenter on that post) noticed, this handy hasher they provided doesn't handle Encrypted passwords (despite the confusing lingo they use in the post that seems to indicate that it does). It seems like it should, considering they do bring across the password format into the database, but then curiously the code doesn't use it, instead having
int passwordformat = 1;
which is for hashed passwords. What I needed was one that would handle my scenario which is encrypted passwords using the System.Web/MachineKey configuration element's decryptionKey.
If you also are in such a predicament, and are using the AES algorithm (as defined in the decryption property of the machineKey) then my answer below should come to your rescue.
First, let's talk real quick about what the SqlMembershipProvider is doing under the hood. The provider combines the salt, converted to a byte[] with the password, encoded as a unicode byte array, into a single larger byte array, by concatenating the two together. Pretty straightforward. Then it passes this off, through an abstraction (MembershipAdapter) to the MachineKeySection where the real work is done.
The important part about that handoff is that it instructs the MachineKeySection to use an empty IV (intialization vector) and also to perform no signing. That empty IV is the real lynchpin, because the machineKey element has no IV property, so if you've scratched your head and wondered how the providers were handling this aspect, that's how. Once you know that (from digging around the source code) then you can distill down the encryption code in the MachineKeySection code and combine it with the membership provider's code to arrive at a more complete hasher. Full source:
public class SQLPasswordHasher : PasswordHasher
{
public override string HashPassword(string password)
{
return base.HashPassword(password);
}
public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
{
string[] passwordProperties = hashedPassword.Split('|');
if (passwordProperties.Length != 3)
{
return base.VerifyHashedPassword(hashedPassword, providedPassword);
}
else
{
string passwordHash = passwordProperties[0];
int passwordformat = int.Parse(passwordProperties[1]);
string salt = passwordProperties[2];
if (String.Equals(EncryptPassword(providedPassword, passwordformat, salt), passwordHash, StringComparison.CurrentCultureIgnoreCase))
{
return PasswordVerificationResult.SuccessRehashNeeded;
}
else
{
return PasswordVerificationResult.Failed;
}
}
}
//This is copied from the existing SQL providers and is provided only for back-compat.
private string EncryptPassword(string pass, int passwordFormat, string salt)
{
if (passwordFormat == 0) // MembershipPasswordFormat.Clear
return pass;
byte[] bIn = Encoding.Unicode.GetBytes(pass);
byte[] bSalt = Convert.FromBase64String(salt);
byte[] bRet = null;
if (passwordFormat == 1)
{ // MembershipPasswordFormat.Hashed
HashAlgorithm hm = HashAlgorithm.Create("SHA1");
if (hm is KeyedHashAlgorithm)
{
KeyedHashAlgorithm kha = (KeyedHashAlgorithm)hm;
if (kha.Key.Length == bSalt.Length)
{
kha.Key = bSalt;
}
else if (kha.Key.Length < bSalt.Length)
{
byte[] bKey = new byte[kha.Key.Length];
Buffer.BlockCopy(bSalt, 0, bKey, 0, bKey.Length);
kha.Key = bKey;
}
else
{
byte[] bKey = new byte[kha.Key.Length];
for (int iter = 0; iter < bKey.Length;)
{
int len = Math.Min(bSalt.Length, bKey.Length - iter);
Buffer.BlockCopy(bSalt, 0, bKey, iter, len);
iter += len;
}
kha.Key = bKey;
}
bRet = kha.ComputeHash(bIn);
}
else
{
byte[] bAll = new byte[bSalt.Length + bIn.Length];
Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);
bRet = hm.ComputeHash(bAll);
}
}
else //MembershipPasswordFormat.Encrypted, aka 2
{
byte[] bEncrypt = new byte[bSalt.Length + bIn.Length];
Buffer.BlockCopy(bSalt, 0, bEncrypt, 0, bSalt.Length);
Buffer.BlockCopy(bIn, 0, bEncrypt, bSalt.Length, bIn.Length);
// Distilled from MachineKeyConfigSection EncryptOrDecryptData function, assuming AES algo and paswordCompatMode=Framework20 (the default)
using (var stream = new MemoryStream())
{
var aes = new AesCryptoServiceProvider();
aes.Key = HexStringToByteArray(MachineKey.DecryptionKey);
aes.GenerateIV();
aes.IV = new byte[aes.IV.Length];
using (var transform = aes.CreateEncryptor())
{
using (var stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
stream2.Write(bEncrypt, 0, bEncrypt.Length);
stream2.FlushFinalBlock();
bRet = stream.ToArray();
}
}
}
}
return Convert.ToBase64String(bRet);
}
public static byte[] HexStringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
private static MachineKeySection MachineKey
{
get
{
//Get encryption and decryption key information from the configuration.
System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
return cfg.GetSection("system.web/machineKey") as MachineKeySection;
}
}
}
If you have a different algorithm, then the steps will be very close to the same, but you may want to first dive into the source for MachineKeySection and carefully walkthrough how they're initializing things. Happy Coding!
I am trying to encrypt a byte[] using the following methods but when I decrypt it my byte[] is bigger than when I started and I think its to do with padding but I am not sure how to solve it.
The method isnt finished yet (I know its bad to append the key + iv like my example but its for testing purpose to get it working before I move on).
So when I try to open the file afterwards (tested with MS Word file) I get a message saying the file is damaged and would I like to repair it.
Encrypt Method
public byte[] Encrypt(byte[] dataToEncrypt) {
// Check arguments.
if (dataToEncrypt == null || dataToEncrypt.Length <= 0) {
throw new ArgumentNullException("dataToEncrypt");
}
byte[] encryptedData;
byte[] key;
byte[] iv;
// Create an Aes object
using (Aes aesAlg = Aes.Create()) {
key = aesAlg.Key;
iv = aesAlg.IV;
// Create a encrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream memoryStream = new MemoryStream()) {
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) {
cryptoStream.Write(dataToEncrypt, 0, dataToEncrypt.Length);
cryptoStream.FlushFinalBlock();
encryptedData = memoryStream.ToArray();
}
}
}
byte[] result = new byte[encryptedData.Length + KEY_SIZE + IV_SIZE];
Buffer.BlockCopy(key, 0, result, 0, KEY_SIZE);
Buffer.BlockCopy(iv, 0, result, KEY_SIZE, IV_SIZE);
Buffer.BlockCopy(encryptedData, 0, result, KEY_SIZE + IV_SIZE, encryptedData.Length);
return result;
}
Decrypt Method
public byte[] Decrypt(byte[] encryptedData) {
// Check arguments.
if (encryptedData == null || encryptedData.Length <= 0) {
throw new ArgumentNullException("encryptedData");
}
byte[] storedKey = new byte[KEY_SIZE];
byte[] storedIV = new byte[IV_SIZE];
byte[] dataToDecrypt = new byte[encryptedData.Length - (KEY_SIZE + IV_SIZE)];
Buffer.BlockCopy(encryptedData, 0, storedKey, 0, KEY_SIZE);
Buffer.BlockCopy(encryptedData, KEY_SIZE, storedIV, 0, IV_SIZE);
Buffer.BlockCopy(encryptedData, KEY_SIZE + IV_SIZE, dataToDecrypt, 0, encryptedData.Length - (KEY_SIZE + IV_SIZE));
byte[] decryptedData = null;
// Create an AesCryptoServiceProvider object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create()) {
aesAlg.Key = storedKey;
aesAlg.IV = storedIV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream memoryStream = new MemoryStream(dataToDecrypt)) {
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) {
cryptoStream.Read(dataToDecrypt, 0, dataToDecrypt.Length);
decryptedData = memoryStream.ToArray();
}
}
}
return decryptedData;
}
You are assuming that the entire buffer is plaintext data as well. You should only return that part of the buffer that contains the plaintext data (using the response of Read to see how much bytes are returned). The encrypted data is usually larger because of the padding.
As a single read method isn't good practice with regards to stream handling. You need to read until the end of the stream is reached. Otherwise you may go from having too much data to having too little.
I have to write a code in Node js using crypto module (as I am not allowed to use any module apart from MIT licensed). I need to generate a key pair and encrypt some message with the pulic key and decrypt it with private key. The first part i.e generation of key pair is done. I am not getting any clue how to use crypto modue to encrypt and decrypt some message using the same key pair.
This should do what you want:
const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto');
//generate a key pair RSA type encryption with a .pem format
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
}
});
// print out the generated keys
console.log(`PublicKey: ${publicKey}`);
console.log(`PrivateKey: ${privateKey}`);
//message to be encrypted
var toEncrypt = "my secret text to be encrypted";
var encryptBuffer = Buffer.from(toEncrypt);
//encrypt using public key
var encrypted = publicEncrypt(publicKey,encryptBuffer);
//print out the text and cyphertext
console.log("Text to be encrypted:");
console.log(toEncrypt);
console.log("cipherText:");
console.log(encrypted.toString());
//decrypt the cyphertext using the private key
var decryptBuffer = Buffer.from(encrypted.toString("base64"), "base64");
var decrypted = privateDecrypt(privateKey,decryptBuffer);
//print out the decrypted text
console.log("decripted Text:");
console.log(decrypted.toString());
It generates a key pair that can be used to encrypt and decrypt a message.
In the Node Documentation for the Crypto lib is the following example:
var crypto = require('crypto');
var alice = crypto.getDiffieHellman('modp5');
var bob = crypto.getDiffieHellman('modp5');
alice.generateKeys();
bob.generateKeys();
var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);
This example shows how to compute a shared secret which can then be used with .createCipher() and .createDecipher() as shown below:
var encrypt64 = function(aMsg, aSecret) {
var cipher, tRet;
cipher = crypto.createCipher('aes-256-cbc', aSecret);
tRet = cipher.update(aMsg, 'utf8', 'base64');
tRet += cipher.final('base64');
return tRet;
};
var decrypt64 = function(aMsg, aSecret) {
var decipher, tRet;
decipher = crypto.createDecipher('aes-256-cbc', aSecret);
tRet = decipher.update(aMsg.replace(/\s/g, "+"), 'base64', 'utf8');
tRet += decipher.final('utf8');
return tRet;
};