Using CommonCrypto to generate a salted key - objective-c

This is how I have been generating my cryptographic keys until now:
unsigned char *salt; //8 salt bytes were created earlier
unsigned char *password; //password was obtained earlier
int passwordLength; //password length as well
unsigned char evp_key[EVP_MAX_KEY_LENGTH] = {"\0"};
unsigned char iv[EVP_MAX_IV_LENGTH];
EVP_BytesToKey(cipher, EVP_md5(), salt, password, //cipher is also given
passwordLength,
1, evp_key, iv);
The result is a key and an “initial value.” I can then use these two (evp_key and iv) along with the given cipher to encrypt my data.
Now that with Lion, Apple has deprecated the above code, I have the following question:
Question: How do I do the same thing with CommonCrypto? I just came across the CCKeyDerivationPBKDF() function. Is this the one I’m looking for? I can’t see how this is the case, since I don’t get any “initial value” back. I don’t know how to compare this CommonCrypto function with the old method.
In particular: This new function doesn’t seem to even support the MD5 algorithm—only the SHA1. How, then, can I create new code that is backwards compatible with my old codebase (and files it has created)?

I found the solution. To me, it seems impossible to derive the keys exactly the way OpenSSL does using any Apple’s methods. Instead, I just had to read how OpenSSL derive the key and initialization vector in the section “Key Derivation Algorithm” on the page http://www.openssl.org/docs/crypto/EVP_BytesToKey.html and simply mimic that.

Related

How to create symmetric encryption key with Google Tink?

I have a key (say) "thisist0psecret" that I want to use as a symmetric encryption/decryption key with the Google Tink library. I am baffled that I am unable to do this simple thing. I can generate new keys (using various templates AES128_GCM, etc.), serialize them and then read them back with KeysetReader. But, for the life of me, I cannot figure out how to create a symmetric key with the specific key bytes that I specify.
I am able to do the following, for example, with Tink:
KeysetHandle ksh = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
Aead aead = AeadFactory.getPrimitive(ksh);
String pt = "hello, world!";
byte[] encbytes = aead.encrypt(pt.getBytes(), null);
byte[] decbytes = aead.decrypt(encbytes, null);
String orig = new String(decbytes);
assert(pt.equals(orig));
But I want to set the symmetric key string to be a set of bytes that I specify such as "thisist0psecret" and then encrypt this key with the public key of the user who will do the decryption.
Any Google Tink experts here that can shed some light?
I'm the lead developer for Tink.
If your key is randomly generated, you can use the subtle API directly, see: https://github.com/google/tink/blob/master/java_src/src/main/java/com/google/crypto/tink/subtle/AesGcmJce.java.
This is not recommended because the subtle layer might change without notice (thought it's been relatively stable in the history of Tink).
If your key is a password you want to derive a key from it using something like Scrypt or PBKDF2. We haven't yet support native password-based encryption in Tink, please file a feature request and we'll see how we can help.

PBKDF2 with HMAC in Java

I am working on a Java project where I must ensure the confidentiality and integrity of users password saved in a plaintext file.
To do so, I will write only a hash of the password in the file. More specifically, my intention is to write the hash of the password and a random salt, plus the random salt itself, to avoid the use of rainbow and lookup tables. I also want to use key-stretching with PBKDF2, to make the computation of the hash computationally expensive.
Finally, I would like to use a keyed hash algorithm, HMAC, for a final layer of protection.
I am trying to implement my thoughts in a Java code, and I have found some examples of the operations that I have presented above:
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
return skf.generateSecret(spec).getEncoded();
}
The thing that I really cannot understand is how to input my secret key as the key used by the HMAC algorithm, as it doesn't seem an input to the function. I have looked through the Java documentation, but I cannot find a solution to my question.
At this point, I am not really sure if I understood correctly how the different part of the encryption mechanism work, so I would accept any help on the topic.
I think I see the confusion. You're apparently expecting your code to apply PBKDF2 then HMAC-SHA-1. That's not how it works: HMAC-SHA-1 is used inside PBKDF2.
The gist of PBKDF2 is to apply a function repeatedly which has the following properties:
it takes two arguments;
it returns a fixed-size value;
it is practically undistinguishable from a pseudo-random function.
HMAC-SHA-1 is such a function, and a common choice. There are other variants of PBKDF2, using HMAC-MD5, HMAC-SHA-256, or other functions (but these variants aren't in the basic Java library).
PBKDF2 takes two data inputs (plus some configuration inputs): the password, and a salt. If you want to include a secret value in the calculation, PBKDF2's input is the place for it: don't tack on a custom scheme on top of that (doing your own crypto is a recipe for doing it wrong). Append the pepper (secret value common to all accounts) to the salt (public value that varies between accounts).
Note that pepper is of limited usefulness. It's only useful if the hashes and the pepper secret value are stored in different places — for example, if the hashes are in a database and the pepper is in a disk file that is not directly vulnerable to SQL injection attacks.

Xcode Openssl RSA decryption function needed

I am reading an encrypted string from an application in xcode and I have to write a function that uses RSA decryption to decode and display the message.
I am completely lost on where to begin with this.
I have Openssl complied in xcode and I am using the openssl/rsa.h file.
I am trying to use the function:
RSA_private_decrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding);
But then I'd read somewhere on the Openssl main site that the function just returns a number and not the actual string. I also have no idea what paramenters to pass through.
The only reference I have found is the openssl/rsa.h file and looking at the functions it contains.
I've tried doing some research the past couple hours but I have no found any answers.
I was wondering if there is a simple function that I can pass my encrypted string and my private key (using a file or hardcoded) and it can return the decrypted string?
If not is there a guide on how to use Openssl with Objective C programming?
Please let me know if you need more information on the issue.
Thank you in advance.
You may want to look Apple's example which uses security transforms (this avoids openssl) in their Security Overview.
With a bit of luck you can do things with apple transforms and go with that programme.
If not - or if for some reason you really want to use openssl; then the openssl source contains the example file openssl-0.9.8t/apps/rsa.c which pretty much allows for selective cut-and-paste to make things work.
Doing man RSA_private_decrypt from the command line will show you the manual page (or from within Xcode to the man page). Or see http://www.openssl.org/docs/crypto/RSA_public_encrypt.html.
Example use for the above:
unsigned char in[] = { 1, 2, ... byte array to decrypt };
// size of that in byte array
int inlen = sizeof(in);
// output buffer size depends on the key type.
char * out = malloc(RSA_size(rsa));
int e = RSA_private_decrypt(inlen, in, out, rsa, RSA_PKCS1_PADDING);
where padding is one of the values from the man-page.
The value of rsa is a bit more complex to initialise as this is where you set up your keys and what not. Check the above rsa.c file for examples of various ways of filling it - it normally boils down to something like:
EVP_PKEY *pkey = load_key( ... , password,... );
rsa = EVP_PKEY_get1_RSA(pkey);
where load_key is borrowed from the app examples of openssl.

Are RSA signatures unique?

I want to know if RSA signatures are unique for a data.
Suppose I have a "hello" string. The method of computing the RSA signature is firstly to get the sha1 digest(these are , I know, unqiue for data), then add a header with OID and padding scheme mentioned and do some mathematical jiggle to give the signature.
Now assuming padding is same, will the signature generating by openSSL or Bouncy Castle be same?
If yes, my only fear is, won't it be easy to get back the "text"/data??
I actaully tried to do an RSA signature of some data and the signatures from OpenSSL and BC was different. I repeated it but got same signature again and again for each of them. I realized that the two signatures of the methods were different because of the difference in padding. However I am still not sure why the signatures of each of the libs are same all the time I repeat them. Can somebody please give an easy explanation?
The "usual" padding scheme, described in PKCS#1 as the "old-style, v1.5" padding, is deterministic. It works like this:
The data to sign is hashed (e.g. with SHA-1).
A fixed header is added; that header is actually an ASN.1 structure which identifies the hash function which was just used to process the data.
Padding bytes are added (on the left): 0x00, then 0x01, then some 0xFF bytes, then 0x00. The number of 0xFF bytes is adjusted so that the resulting total length is exactly the byte length of the modulus (i.e. 128 bytes for a 1024-bit RSA key).
The padded value is converted to an integer (which is less than the modulus), which goes through the modular exponentiation which is at the core of RSA. The result is converted back to a sequence of bytes, and that's the signature.
All these operations are deterministic, there is no random, hence it is normal and expected that signing the same data with the same key and the same hash function will yield the same signature ever and ever.
However there is a slight underspecification in the ASN.1-based fixed header. This is a structure which identifies the hash function, along with "parameters" for that hash function. Usual hash functions take no parameters, hence the parameters shall be represented with either a special "NULL" value (which takes a few bytes), or be omitted altogether: both representations are acceptable (although the former is supposedly preferred). So, the raw effect is that there are two versions of the "fixed header", for a given hash function. OpenSSL and Bouncycastle do not use the same header. However, signature verifiers are supposed to accept both.
PKCS#1 also describes a newer padding scheme, called PSS, which is more complex but with a stronger security proof. PSS includes a bunch of random bytes, so you will get a distinct signature every time.
Signatures are not a privacy mechanism; it's not considered a problem if you can get the plaintext back out. If your message must be kept secret, then encrypt as well as sign.
Nevertheless, remember that RSA signatures are created using a signer's private key. Given such a signature, you can use the signer's public key to "undo" the RSA transform (raise the message's signature to e, mod n) and get out the SHA1 or other hash value that was provided as its input. You still can't undo the hash function to get the input plaintext corresponding to a signature that has become detached from its message.
RSA for encryption is a different matter. Padding methods for encryption here do include random data in order to defeat traffic analysis.
This is why you add a salt/initialisation vector on top of your key. That way it shouldn't be possible to tell which records came from the same plaintext.

How do i get the BITS length from NSUintger, NSString

I need to get the BIT length from NSUinteger or NSString
How i can get the bit length?
Thanks
If I'm understanding the question correctly (it is kind of odd, but... hey... so am I):
sizeof(NSUInteger) * 8
[aString maximumLengthOfBytesUsingEncoding: ...] * 8
For NSNumber, a subclass of NSValue, things get a little bit trickier. You'll need to call -objCType, then determine the bit length from that.
OP: I really think you need to organize your thoughts and ask a single, coherent question that, at a minimum, gives an overview of what you're trying to accomplish. So far you have asked at least four questions that are all minor variations of each other.
To other people answering this question: From the context of his other questions, he's trying to do some bignum crypto (ala RSA), or some other bignum number theory stuff (needs to do powermod()). Again, based on the context of his other questions, what he's asking in this question is how to do floor(log2(X)) + 1 where X is an arbitrary data type (hence the NSString).
I have a RSA Exponent key value which is supposed to be a biginteger but i have it in NSString/NSdata with full value in(UTF8 encoded)
As Part of RSA encryption , i need to do the following in the Iphone Env
1.I need to find the bit length of the above exponent value
2.I need to do arithmatic operations on exponent and modulus values including PowMod
3.so which data type i can use (uint64_t or NSNUmber or NSUinteger) for arithmatic operations as well as holding the bigint result value.
4.do i need to go for a specfic bigint implementation, can i able to manage with the above existing iphone data types for bigint ?
5. those external bigint implementations expect to port openssl or gmp lib to Iphone ?