encryption,aes,crypto++ , Can I specify the nonce and counter in AES encryption counter mode?

Can I specify the nonce and counter in AES encryption counter mode?


Tag: encryption,aes,crypto++

I'm trying to use the library Crypto++ to make AES Counter mode based encryption/decryption

I want to split the IV value into nonce and counter.
Is there any API that directly takes the nonce and counter to construct the IV ?

I did the following to achieve it

byte counter[AES::BLOCKSIZE/2] = {0x0};     // initialized to zero : 64 bit counter
string counterstr ;
byte nonce[AES::BLOCKSIZE/2];                // 64 bit nonce 
string noncestr ;
prng.GenerateBlock(nonce, sizeof(nonce));
StringSource(nonce, sizeof(nonce), true,
    new HexEncoder(
    new StringSink(noncestr)
    ) // HexEncoder
StringSource(counter, sizeof(counter), true,
    new HexEncoder(
    new StringSink(counterstr)
    ) // HexEncoder
SecByteBlock no = HexDecodeString(noncestr);
SecByteBlock ctr = HexDecodeString(counterstr);
string ivv = noncestr + counterstr;
SecByteBlock ivvb = HexDecodeString(ivv);

then I use

e.SetKeyWithIV(key, sizeof(key), iv);



Is this the only way to achieve this or is there any other easier way?

No. The increment function operates on the full 128-bit block. See CTR mode and Counter Increment on the Crypto++ wiki.

The longer answer is Yes if you provide your own IncrementCounter function. The longer answer can be Yes if you use the high order bits for the nonce and low order bits for the counter (see more below).

Does the counter value increment automatically when doing encryption or decryption of blocks?


This one is trivial, should I specify another nonce value for each block?

No. The counter is incremented.

Is there any API that directly takes the nonce and counter to construct the IV ?

No. In more practical terms, there is a limit to how much plain text can be encrypted under a key/nonce pair (or security context). I think its well below 2 GB. If my recollection is correct, then you will have to re-key long before your counter gets into the high 64-bits.

In effect, that means you can use the high 64-bits as the random nonce, and use the lower 64-bits as the counter. So your code would look something like:

byte counter[AES::BLOCKSIZE] = {0};
prng.GenerateBlock(counter, 8);

After the code above executes, the high 64-bits will be random, and the low 64-bits will start at 0 and serve as the counter.

Since 2 GB is about the limit, you can use a 12-4 split rather than a 8-8 split:

byte counter[AES::BLOCKSIZE] = {0};
prng.GenerateBlock(counter, 12);

After the code above executes, the high 96-bits will be random, and the low 32-bits will start at 0 and serve as the counter.

Related, never reuse a nonce. Each message must have its own, unique security context. That usually means a unique nonce (the other option is to provide a unique key for each message). Otherwise, you can trivially recover the key with an XOR.


iOS “Data Protection” depends on user passcode set or not?

When developing iOS Apps one can chose to add the Capability "Data Protection", which then offers more "protection". What, after a lot of searching and reading, is still unclear to me: will the files declared to be secured with "complete protection" be encrypted even if the user doesn't set a...

DES encrypted value mismatching android and ios

IOS code is #import "DESCodec.h" #import <CommonCrypto/CommonCryptor.h> @implementation DESCodec { NSString *key; } -(id) init{ self=[super init]; if(self){ [email protected]"12345678"; } return self; } -(NSString *) decode:(NSString *)encoded{ NSData *inputData = [[NSData alloc] initWithBase64EncodedString:encoded options:0]; NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding]; size_t outLength; NSMutableData *outputData = [NSMutableData dataWithLength:(inputData.length + kCCBlockSizeDES)]; CCCryptorStatus result...

AES Encryption in Java differs from PHP

Frequent visitor but first-time poster. I've been doing much searching but can't find an adequate explanation for why this: public class encryption_test { private static final String text_encoding = "UTF-8"; private byte [] byte_array (String input) throws Exception { return input.getBytes (text_encoding); }// byte_array; private byte [] encrypt (String text)...

Code fails for decrypting without salt or iv in Java

I have a ciphertext and a 256-bit key to decrypt it, using AES. There is no salt or iv. I am using Java. I have implemented many of the solutions online, but they all use salts and input vectors. The following builds fine, but fails at runtime: "Salt not found."...

SQL-Server Verify SHA2_512 hash procedure

Consider this method declare @pswd nvarchar(max); set @pswd = '2YKRCqHv'; Select orig = a.Hash, hashA = 0x0200 + a.Salt + Hashbytes('SHA2_512', cast('2YKRCqHv' as varbinary(max)) + a.Salt), hashB = 0x0200 + a.Salt + Hashbytes('SHA2_512', cast(@pswd as varbinary(max)) + a.Salt) from DB a where a.Hash = 0x0200 + a.Salt+ Hashbytes('SHA2_512', cast('2YKRCqHv' as...

Implement same RSA encryption on iOS and Android

I have iOS sources for data encoding and I try to implement same encoding in Android app. iOS sources: - (NSString *)encryptRSA:(NSString *)plainTextString useKeyWithTag:(NSString *)tag withSecPadding:(SecPadding)padding { SecKeyRef publicKey = [self _getPublicKeyRefByTag:tag]; size_t cipherBufferSize = SecKeyGetBlockSize(publicKey); uint8_t *cipherBuffer = malloc(cipherBufferSize); uint8_t *nonce = (uint8_t *)[plainTextString UTF8String]; SecKeyEncrypt(publicKey, padding, nonce, strlen(...

Getting variable encryption results with VB.Net and DES

I'm working on an semi-internal encryption process for somewhat sensitive information. Email addresses and the like. I'm working with a few other developers at some sister companies on the project, and the requirements are that everyone's encryption can talk to everyone else's. We use a global password, encrypt and decrypt...

How to use AES CBC using a key longer than 256 bits in Python

Anyone have a way to encrypt/decrypt using Python to handle AES in CBC mode with a key of 1024 bits (128 bytes)? All the AES pkgs found so far seem to be limited to 256 bit keys. My crypto background is limited....

C# AES and RSA File Encryption - How to use IV?

I'm writing a program at the moment that works under the following scenario: I've got some confidential log files that I need to backup to a server. I have a program that generates these log files every day. These log files would rarely if ever need to be opened. I...

MySQL AES_DECRYPT wrong/strange result

Under my development machine WAMP, AES_ENCRYPT and AES_DECRYPT is not working as required, also i tested with ENCODE and DECODE and same happen... I'm not understading why... SELECT AES_ENCRYPT('text', SHA1('My secret passphrase')) as enc, AES_DECRYPT(AES_ENCRYPT('text', SHA1('My secret passphrase')), SHA1('My secret passphrase')) as denc Result: enc : 3278167d9d630327c74d83067964c9b6 denc: 74657874 text...

Mounting GEOM_ELI Encrypted ZFS Pool as root

I have a 3 Disk RAIDz1 Pool, encrypted with AES128 in GEOM_ELI, that I have been using in FreeNAS since version 8. There have been many zpool upgrades, and over all I am very happy with ZFS. Lately however I have been growing frustrated with FreeNAS. Largely many bugs that...

Attempting to use SHA1 hashing to send password to Google

I am currently working on a program with Google's Directory API to reset the password of someone in my domain. I have it all working, but I would like to send an encrypted password to Google instead of plaintext. Since the API seems limited in what I can use to...

Android encryption and decryption of text fails

I try to encrypt some text (here it is named code) and decrypt it again. For this i use a 4 digit Pin which is salted. After this the text is encrypted, also again some Base64 decoding, so i can safely output the String again. As i understand i have...

Reverse ^ operator for decryption

I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

Symmetric encryption (AES) in Apache Thrift

I have two applications that interact using Thrift. They share the same secret key and I need to encrypt their messages. It makes sense to use symmetric algorithm (AES, for example), but I haven't found any library to do this. So I made a research and see following options: Use...

DES decryption only working when the key is 0s

I'm experiencing a weird behaviour here. Whenever I set the DES key to 0s the decryption works, but if I set the key to anything else then the decryption returns an unreadable string: Main method: static void Main(string[] args) { //Decryption works! byte[] key0 = new byte[] { 0x00, 0x00,...

Ways to encrypt a whole directory instead of just a file

I want to use GPG for local encryption only, and after reading the man file, I'm doing the following in order to encrypt a whole directory: I zip the directory with a password "zip -r -e foo foo", then I encrypt it with "gpg -c foo.zip" using a passphrase. Is...

Encrypted Querystring in URL getting changed to lowercase in Outlook

I am providing a CANCEL button in a registration email, so that the user can click the link and cancel their registration. This works fine except Outlook is converting links to lowercase. So when the user clicks the link, I can't decrypt the URL because the encrypted querystring is now...

Can I throw a message fault back to a WCF client from a routing service

My company has long used ASPX and windows services through a routing program to manage the connections and allow our datacenters to control where the clients make connections. Just recently we started using MVC and WCF. Yes in 2015 we are just moving to these things. Anyway they figured out...

Receiving unexpected indent with encryption script [closed]

So I've been working on this script to just create a simple encrypted message and write the cipher text to a file. I keep getting an error for "unexpected indent" on line 32 and I can't figure out why. I've taken 2 pieces of code I found online and tried...

Get RSA keys in a “simple” form

How can I get keys generated by OpenSSL in RAW form? I mean I can't decode my encoded messages in any of online tools. What actions should I do to distribute my keys to other clients (in other apps and web-apps) in proper forms? My generation code is: void VS_CarrierNet::generateKeys()...

LC3 assembly-unable to print the right character

I have been trying to make a program that decrypts a text that is being read from a file under the following condiditons: The adress of the first element of the file is 5001.Each letter is encrypted twice:The first time with Ceasar encryption and the second time with XOR encryption.The...

RSA encryption in Android and Java

I would like to encrypt a String with RSA encryption. My public/private keys were generated and stored in DB. In android, I use this code: public static String encryptRSAToString(String text, String strPublicKey) { byte[] cipherText = null; String strEncryInfoData=""; try { KeyFactory keyFac = KeyFactory.getInstance("RSA"); KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(strPublicKey.trim().getBytes(),...

AES with PKCS#5 padding

In quite a few places, I see Java code that uses AES with PKCS#5 padding. I do not understand how this could possible work. PKCS#5 padding is meant to be used with ciphers that have a block size of <= 8 bytes. The block size for AES is 16 bytes....

AES encryption/decryption iOs and .Net

I used CocoaSecurity and RNCryptor to encrypt NSString on iOs app, and on the server side (.NET) tried to decrypt it using one of the many function found on the web, but no luck. Also AES decryption online tools, fail to decrypt. Can somebody provides a working example of NSString...

gzip and pipe to output (performance consideration)

q1) Can i check if I do a gzip -c file | encrypt (some parameters) a) does gzip print out the output line by line and pipe it to the encrypt function or b) gzip will be perform 1st, then the output will be pipe all at once to the...

How to migrate from sha256 encryption to bcrypt for php?

For Login : $rows = $sql->fetch(PDO::FETCH_ASSOC); $us_id = $rows['id']; $us_pass = $rows['password']; $us_salt = $rows['password_salt']; $status = $rows['attempt']; $saltedPass = hash('sha256', "{$password}{$this->passwordSalt}{$us_salt}"); For Register : $randomSalt = $this->rand_string(20); $saltedPass = hash('sha256', "{$password}{$this->passwordSalt}{$randomSalt}"); How can this sha256 encryption method be converted to bcrypt ?...

Digital Signature in java / android (RSA keys)

I would like to generate a digital signature in my java/android project with a private key(RSA) stored in DB. My 2 keys was generated with the below code (project is in production and I cannot change it): // Get keys pair (RSA) KeyPair rsaKyePair = createKeyPair(); // Get private/ public...

Issues with AES Encryption using SynCrypto

Am trying to encrypt a file using SynCrypto.pas with AES 256, but it fails if I try to encrypt a file whose size is not a multiple of 16 bytes. The decrypted data contains junk. Example: Original string in txt file we are testing the file Encrypted String [ù[„|wáî}f *!4ìÙw¬•ü¨s...

File security System in java? [on hold]

i'm new to java world.I have a idea about file secure system.When i add a file to the application it will encrypt and store a folder in the installation path.If i need to see the file ,i need to login with my username and password and the file will automatically...

can not insert MCRYPT encrypted data to the database

I'm using MCRYPT to encrypt sensitive data and save them to the database. The encrypted data look like this (non-encrypted data above the encrypted data) then insert to the MySQL PDO database as usual in a text field utf8_unicode_ci but the result is empty most of the times. Sometimes it...

Encryption of strings using AES 128 in Java/grails

I would like to encrypt 3 strings using AES 128 in Java / Grails, and using the code below, but i get the error "An error occurred when encrypting", can someone tell me what is wrong with my code, how to fix it. thanks in advance and to Stackoverflow. String...

Problems generating a self-signed 1024-bit X509Certificate2 using the RSA AES provider

I am trying to generate an X509Certificate2 object using the Microsoft AES Cryptographic Provider: CALG_AES_256 (0x00006610) 256 bit AES. This algorithm is supported by the Microsoft AES Cryptographic Provider. My problem is that my call to CryptGenKey(providerContext, 0x6610, 0x4000001, out cryptKey) fails with the following error: An unhandled exception of...

vb.net AES decryption returns “data is incomplete block”

I'm aware of the other thread on this issue (AES decryption error " The input data is not a complete block." Error vb.net), but I'm either not implementing the solutions offered there correctly, or something about my particular variant of this issue isn't covered by those solutions. In any event...

SSL/TLS: Why will the server be the only one to be able to decrypt the encrypted number if it's a public key?

Wouldn't anyone else be able to decrypt it too using the public key? Or is it saying that it will be decrypted with a private key. If that's the case how could something be encrypted with one key and decrypted with another? This is in reference to this wikipedia article....

Issue with understanding keystore and ssl

These are the facts: I have a client(android)-server(java - Ubuntu 14.04)-program with which I transmit my gps-data from my smartphone every 5 minutes to the server saving it into a mysql-database. My problem is that I do not want to transmit my GPS data plain. So I want to use...

Can I specify the nonce and counter in AES encryption counter mode?

I'm trying to use the library Crypto++ to make AES Counter mode based encryption/decryption I want to split the IV value into nonce and counter. Is there any API that directly takes the nonce and counter to construct the IV ? I did the following to achieve it byte counter[AES::BLOCKSIZE/2]...

Decrypt an encrypted text

I got a textbox and a 'decrypt' button in my Windows Form Application where I put an encrypted string in there and try to decrypt it but the problem is this. First, I got this class code called DataEncryptor from a guy on this website: public class DataEncryptor { TripleDESCryptoServiceProvider...

(Android) Encrypting data disallowing awarness of the method used in the source code

I'm currently helping on a project in which some data must be encrypted using some symmetric algorithm (a second level of encryption above the SSL/TLS connection which is currently implemented). The problem is that if we extract the source code from the .apk (using tools like ApkTool, dex2jar & Java...