TCL code that can encrypt and decrypt a string - encryption

I need a piece of code that defines functions which can encrypt and decrypt a piece of string. What I basically want is that the string should not be visible to third-party users, so that when the string originates in one file, it is converted to, say, an integer value using the encrypt function and then it is passed as parameter to another file. There the decrpyt function then decrypts it back and uses the string to perform actions on it.
Any suggestions or already available codes will be just fine!
Please help me out. Thanks!

Install tcllib. There are several standard encryption algorithms implemented in tcllib.
The following encryption algorithms are available:
blowfish: http://tcllib.sourceforge.net/doc/blowfish.html
aes: http://tcllib.sourceforge.net/doc/aes.html
des (including triple des): http://tcllib.sourceforge.net/doc/des.html
rc4: http://tcllib.sourceforge.net/doc/rc4.html

The des package in Tcllib should do what you want. It's pretty easy to use:
package require des
set key "12345678"; # Must be 8 bytes long
set msg "abcde"
##### ENCRYPTION
set encryptedMsg [DES::des -dir encrypt -key $key $msg]
# $encryptedMsg is a bunch of bytes; you'll want to send this around...
##### DECRYPTION
set decryptedMsg [DES::des -dir decrypt -key $key $encryptedMsg]
puts "I got '$decryptedMsg'"
Note that DES will pad the message out to a multiple of 8 bytes long.

Please visit the TCL/TK homepage e.g
here:http://wiki.tcl.tk/900
That's just one way of doing it. There will be much more, I'm sure.

Related

Where does Linux openssl AES save the IV [duplicate]

I've generated a random 256 bit symmetric key, in a file, to use for encrypting some data using the OpenSSL command line which I need to decrypt later programmatically using the OpenSSL library. I'm not having success, and I think the problem might be in the initialization vector I'm using (or not using).
I encrypt the data using this command:
/usr/bin/openssl enc -aes-256-cbc -salt -in input_filename -out output_filename -pass file:keyfile
I'm using the following call to initialize the decrypting of the data:
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, keyfile.data(), nullptr))
keyfile is a vector<unsigned char> that holds the 32 bytes of the key. My question is regarding that last parameter. It's supposed to be an initialization vector to the cipher algorithm. I didn't specify an IV when encrypting, so some default must have been used.
Does passing nullptr for that parameter mean "use the default"? Is the default null, and nothing is added to the first cipher block?
I should mention that I'm able to decrypt from the command line without supplying an IV.
What is the default IV when encrypting with EVP_aes_256_cbc() [sic] cipher...
Does passing nullptr for that parameter mean "use the default"? Is the default null, and nothing is added to the first cipher block?
There is none. You have to supply it. For completeness, the IV should be non-predictable.
Non-Predictable is slightly different than both Unique and Random. For example, SSLv3 used to use the last block of ciphertext for the next block's IV. It was Unique, but it was neither Random nor Non-Predictable, and it made SSLv3 vulnerable to chosen plaintext attacks.
Other libraries do clever things like provide a null vector (a string of 0's). Their attackers thank them for it. Also see Why is using a Non-Random IV with CBC Mode a vulnerability? on Stack Overflow and Is AES in CBC mode secure if a known and/or fixed IV is used? on Crypto.SE.
/usr/bin/openssl enc -aes-256-cbc...
I should mention that I'm able to decrypt from the command line without supplying an IV.
OpenSSL uses an internal mashup/key derivation function which takes the password, and derives a key and iv. Its called EVP_BytesToKey, and you can read about it in the man pages. The man pages also say:
If the total key and IV length is less than the digest length and MD5 is used then the derivation algorithm is compatible with PKCS#5 v1.5 otherwise a non standard extension is used to derive the extra data.
There are plenty of examples of EVP_BytesToKey once you know what to look for. Openssl password to key is one in C. How to decrypt file in Java encrypted with openssl command using AES in one in Java.
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, keyfile.data(), nullptr))
I didn't specify an IV when encrypting, so some default must have been used.
Check your return values. A call should have failed somewhere along the path. Maybe not at EVP_DecryptInit_ex, but surely before EVP_DecryptFinal.
If its not failing, then please file a bug report.
EVP_DecryptInit_ex is an interface to the AES decryption primitive. That is just one piece of what you need to decrypt the OpenSSL encryption format. The OpenSSL encryption format is not well documented, but you can work it backwards from the code and some of the docs. The key and IV computation is explained in the EVP_BytesToKey documentation:
The key and IV is derived by concatenating D_1, D_2, etc until enough
data is available for the key and IV. D_i is defined as:
D_i = HASH^count(D_(i-1) || data || salt)
where || denotes concatentaion, D_0 is empty, HASH is the digest
algorithm in use, HASH^1(data) is simply HASH(data), HASH^2(data) is
HASH(HASH(data)) and so on.
The initial bytes are used for the key and the subsequent bytes for the
IV.
"HASH" here is MD5. In practice, this means you compute hashes like this:
Hash0 = ''
Hash1 = MD5(Hash0 + Password + Salt)
Hash2 = MD5(Hash1 + Password + Salt)
Hash3 = MD5(Hash2 + Password + Salt)
...
Then you pull of the bytes you need for the key, and then pull the bytes you need for the IV. For AES-128 that means Hash1 is the key and Hash2 is the IV. For AES-256, the key is Hash1+Hash2 (concatenated, not added) and Hash3 is the IV.
You need to strip off the leading Salted___ header, then use the salt to compute the key and IV. Then you'll have the pieces to feed into EVP_DecryptInit_ex.
Since you're doing this in C++, though, you can probably just dig through the enc code and reuse it (after verifying its license is compatible with your use).
Note that the OpenSSL IV is randomly generated, since it's the output of a hashing process involving a random salt. The security of the first block doesn't depend on the IV being random per se; it just requires that a particular IV+Key pair never be repeated. The OpenSSL process ensures that as long as the random salt is never repeated.
It is possible that using MD5 this way entangles the key and IV in a way that leaks information, but I've never seen an analysis that claims that. If you have to use the OpenSSL format, I wouldn't have any hesitations over its IV generation. The big problems with the OpenSSL format is that it's fast to brute force (4 rounds of MD5 is not enough stretching) and it lacks any authentication.

How to use Encryption in SAP

SAP servers are capable of encrypting and hashing data. But there doesn't appear to be a suitable API to call. SAP Note 1456433 talks about the class CL_SEC_SXML_XENCRYPTION. The signature of basic encryption is clearly geared towards SSF and unsuitable to basic private key encryption/decryption. I don't want/need envelopes and user certificates. Just private keys.
I found an AES library on GitHub AES library in ABAP and tweaked that to suit us. But it is very slow. I would like to use the encryption libraries SAP has. Clearly, the libraries are there but find a suitably exposed API seems the issue.
Does anybody know how to use basic encryption in SAP?
In SAP ABAP stack, using ABAP.
Eg (a call to use AES-CBC 128, with PKCS7 padding
where only a private key and data to encrypt is required. As example:
public static method encrypt_xstring
importing i_key type xstring
i_data type xstring
i_initialization_vector type xstring optional
i_padding_standard type char10 optional
i_encryption_mode type char10 optional
exporting e_data type xstring
Use case is encrypting data on clients with a private key and sending the data to SAP system. The source supports private keys and libraries like AES-CBC.
And we have encrypted data interchange working.
Next step is to use a supported and faster library.
EDIT: In case anyone needs to encryption / decryption properly in abap
And is looking at the answer. Use class CL_SEC_SXML_WRITER.
CL_SEC_SXML_WRITER was exactly what i was looking for
BUT SAP didnt expose it properly. It is only useful for encryption no decryption.
When interacting with external libraries. Where PKCS7 padding is used and SALTs
or Initialization vectors are required.
SAP offer an ENCRYPT_IV but no Decrypt_IV. Why ????
So you cant use the tool and remain compliant. :(
It is not considered safe to use AES-CBC without IV.
Why would SAP do that ?
ENCRYPT_IV instead of ENCRYPT but no DECRYPT_IV
The offer an Add Padding but no remove padding. OK roll your own padding removal, no big deal. Its like the must be another library for the other direction.
So i can use the tool to encrypt but not decrypt.
My main problem was decrypting quickly strings sent from a mobile device.
So still need to use the old ABAP code for that :(
I have similar requirements and I found the cl_sec_sxml_writer class. Please have a look at the following example. Note that the writer requires XSTRING parameters which is why I'm using conversion classes.
REPORT zged_aes.
DATA lv_message_string TYPE string.
" create message
DATA(lr_conv_sec) = cl_abap_conv_out_ce=>create( ).
lr_conv_sec->write( data = 'This is my secret' ).
" create key
DATA(lr_conv_key) = cl_abap_conv_out_ce=>create( ).
lr_conv_key->write( data = 'MySymmetricKey' ).
" encrypt using AES256
cl_sec_sxml_writer=>encrypt(
EXPORTING
plaintext = lr_conv_sec->get_buffer( )
key = lr_conv_key->get_buffer( )
algorithm = cl_sec_sxml_writer=>co_aes256_algorithm_pem
IMPORTING
ciphertext = DATA(lv_message) ).
" decrypt message
cl_sec_sxml_writer=>decrypt(
EXPORTING
ciphertext = lv_message
key = lr_conv_key->get_buffer( )
algorithm = cl_sec_sxml_writer=>co_aes256_algorithm_pem
IMPORTING
plaintext = DATA(lv_message_decrypted) ).
" convert xstring to string for output
cl_abap_conv_in_ce=>create( input = lv_message_decrypted)->read( IMPORTING data = lv_message_string ).
" output secret message
WRITE lv_message_string.
I tested it on a NetWeaver 7.50 SP 6 system.
I got the ENCRYPT_IV method to work alongside method DECRYPT of class CL_SEC_SXML_WRITER.
The caveat here is that I didn't generate the Symmetric Key and IV by making use of Class cl_abap_conv_out_ce.
I already had my keys and IV from a Java implementation test.
The only thing I needed was to create the Key and IV as an XSTRING and initializing them with the Hex format of my Java implementation (they were in Byte format.
Because of this, I first converted them to Hex and passed those values to the ABAP Xstring types).

MAC variant of MSR DUKPT?

Currently I am working on a ChipCard EMV device decryption. Down below is the related data I have after using the transaction (TLV format as Tag Length Value):
<DFDF54> --- It means KSN
0A
950003000005282005B4
<DFDF59>---- per instruction, it is called Encrypted Data Primative
82 ---- length of value in hex, when more than 255 degits, use 82
00D815F35E7846BF4F34E56D7A42E9D24A59CDDF8C3D565CD3D42A341D4AD84B0B7DBFC02DE72A57770D4F795FAB2CE3A1F253F22E0A8BA8E36FA3EA38EE8C95FEBA3767CDE0D3FBB6741A47BE6734046B8CBFB6044C6EE5F98C9DABCD47BC3FD371F777E7E1DCFA16EE5718FKLIOE51A749C7ECC736CB7780AC39DE062DAACC318219E9AAA26E3C2CE28B82C8D22178DA9CCAE6BBA20AC79AB985FF13611FE80E26C34D27E674C63CAC1933E3F9B1BE319A5D12D16561C334F931A5E619243AF398D9636B0A8DC2ED5C6D1C7C795C00D083C08953BC8679C60
I know BDK for this device is 0123456789ABCDEFFEDCBA9876543210. Per decryption instruction, it mentioned that DFDF59 contains the following tags:
FC<len>/* container for encrypted generic data */
F2<len>/*container for Batch Data*/
... /*Batch Data tags*/
F3<len>/*container for Reversal Data, if any*/
... /*Reversal Data tags*/
Per instruction, it mentioned "MAC variant of MSR DUKPT", where MAC stands for message authentication code, and "Parse the data through TLV format. For encrypted data tag, use TDES_Decrypt_CBC to decrypt it".
I tried to use 3DES DUKPT using KSN, BDK, and encrypted data DFDF59. It wouldn't work. Can anyone in decryption field give me some advice? Our vendor is very reluctant to share their knowledge ...
I have no idea how MAC is really playing a role here in decryption.... I thought MAC is just an integrity check.... I am using session key for 3DES DUKPT that was generated from KSN and BDK. this works for other decryptions in this device, but doesn't solve the DFDF59 (chip card EMV decryption).... That is why I start to wonder whether I am using the right session key or not.... Feel free to just throw ideas out there. Thank you!
If you look closely at DUKPT internals it generates a transaction key out of the current future keys and encryption counter. This 'transaction key' for a specific KSN has several variants (which effectively are just xor masks that you put on the transaction key to differentiate it for PIN, MAC req, MAC rsp, data encryption req and rsp usages). These variants mean that you use a different key to generate PIN and different key to encrypt data (so that you cannot ie. decrypt/attack PINblock when able to select data buffer arbitrarily). Using MAC variant means only that for the encryption operation you will be using a certain mask for the DUKPT transaction key.

how can i set blowfish for CRYPT_BLOWFISH function in php

i use this code for encrypt my data to blwofish but i dont know really to convert to blowfish or other encryption.
echo crypt('ab','$2a$09$anexamplestringforsalt$')."\n";
and i'm try bottom code but it's false
echo CRYPT_BLOWFISH('ab','$2a$09$anexamplestringforsalt$')."\n";
It is the crypt parameter string, that defines which algorithm is used:
$2a : This describes the algorithm (BCrypt) but should be 2y nowadays
$09 : This is the number of rounds and is usually 10 or higher
$anexamplestringforsalt : This should be a really random salt of a given alphabet
To generate a BCrypt hash, it is much safer to use the new password_hash() function though, there exists also a compatibility pack for earlier PHP versions.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

Are there other encoding methods besides base64 that end in "="?

I've inherited a project where the previous developer is using an ASP object called ActiveCrypt.Crypt to encrypt the users password before sending it to the database.
The call uses the encryptvariant() function with a mode of 7, which the only documentation I can find indicates that the encrpytion is 3DES (company is now defunct). The problem is, that the value derived from the function appears to be a base64-encoded string (the trailing single and double "==" are a dead give-away).
Are there any other encodings that frequently end in "=" or "=="? Is anyone familiar with this ActiveCrypt object? I've tried 3DES encoding the password, with the key, then converting to base64, but with no luck. I've also tried inverting the key and the password in case the developer swapped the arguments. Any help would be appreciated.
Some examples using the key "key" (without quotes)
abcdefg: xiupz3RT148=
123456: iDLXPSPPjd4=
test: AWulSF10FR0=
1234567890: 8I48MAg9YWvE3y52VfMYew==
The encodings you show look like 8 and 16 bytes encoded with normal base64. Base64 encodes 3 bytes using 4 characters. DES and 3DES operate with block size of 8 bytes. So the sizes of the base64 text seem to reflect the block size. Furthermore, the output of the base 64 decoding looks fully random.
So after base64 decoding you will have 8 or 16 bytes, which you then will have to decrypt. The key is of course unknown to us, as is the block mode of operation and the padding mode. So you will have to find out those yourself. If the key is not given, it could be hard coded within the application.
Happy hunting.

Resources