Skip to content

Instantly share code, notes, and snippets.

@boucher
Created October 22, 2009 01:33
Show Gist options
  • Select an option

  • Save boucher/215642 to your computer and use it in GitHub Desktop.

Select an option

Save boucher/215642 to your computer and use it in GitHub Desktop.
// Perform symmetric encryption...
unsigned char evp_key[EVP_MAX_KEY_LENGTH] = {"\0"};
EVP_CIPHER_CTX cCtx;
const EVP_CIPHER *cipher;
if (cipherName){
cipher = EVP_get_cipherbyname((const char *)[cipherName UTF8String]);
if (!cipher){
NSLog(@"cannot get cipher with name %@", cipherName);
return nil;
}
} else {
cipher = EVP_bf_cbc();
if (!cipher){
NSLog(@"cannot get cipher with name %@", @"EVP_bf_cbc");
return nil;
}
}
EVP_BytesToKey(cipher, EVP_md5(), NULL,
[[self symmetricKey] bytes], [[self symmetricKey] length], 2048, evp_key, iv);
EVP_CIPHER_CTX_init(&cCtx);
NSLog(@"%s %s", evp_key, iv);
if (!EVP_EncryptInit(&cCtx, cipher, evp_key, iv)) {
NSLog(@"EVP_EncryptInit() failed!");
EVP_CIPHER_CTX_cleanup(&cCtx);
return nil;
}
EVP_CIPHER_CTX_set_key_length(&cCtx, EVP_MAX_KEY_LENGTH);
// The data buffer passed to EVP_EncryptUpdate() should have sufficient room for
// (input_length + cipher_block_size - 1)
outbuf = (unsigned char *)calloc(inlen + EVP_CIPHER_CTX_block_size(&cCtx) - 1, sizeof(unsigned char));
NSAssert(outbuf, @"Cannot allocate memory for buffer!");
if (!EVP_EncryptUpdate(&cCtx, outbuf, &outlen, input, inlen))
{
NSLog(@"EVP_EncryptUpdate() failed!");
EVP_CIPHER_CTX_cleanup(&cCtx);
return nil;
}
if (!EVP_EncryptFinal(&cCtx, outbuf + outlen, &templen))
{
NSLog(@"EVP_EncryptFinal() failed!");
EVP_CIPHER_CTX_cleanup(&cCtx);
return nil;
}
outlen += templen;
EVP_CIPHER_CTX_cleanup(&cCtx);
def des(m,k,t)
(des = OpenSSL::Cipher::Cipher.new('des').send(m)).key = k
des.final << bf.update(t)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment