Raw RSA decryption/signing - blackberry

I'm implementing RSACryptoToken, that is an interface for RSA cryptographic tokens, according to the documentation.
There are twp methods, called decryptRSA and signRSA - they should be implemented.
In documentation there is an info, that they should perform a raw RSA decryption and raw RSA signing operations.
What means raw RSA operation?
Does it mean, without padding?
Does BlackBerry or Bouncy Castle provides such API?

Basically PKCS#1 v1.5 consists of three parts:
the RSA operations themselves,
the PKCS#1 padding and
an ASN.1 encodign of the hash.
The hash is ASN.1 encoded to include an ASN.1 Object Identifier which uniquely specifies the hash that is used, and the value, like this:
DigestInfo ::= SEQUENCE {
digestAlgorithm AlgorithmIdentifier,
digest OCTET STRING
}
This is directly copied from the PKCS#1 specifications (which are pretty readable and publicly available). Note that the encoding is directly specified as bytes as well in the standards.
Blackberry operations only provide 1) and 2), meaning that you have to supply an ASN.1, DER encoded structure containing the hash yourself. No such a structure is defined for the encryption/decryption, only the padding is removed.
Encryption uses random padding (internally) versus non-random padding for signatures. This allows you to encrypt "YES" twice, while an eavesdropper cannot detect if it is YES or NO. The padding is also required to protect the signature against attacks.

I solved the problem, the operations signRSA and decryptRSA should perform the same pure modulus operation
thanks for help

Related

CX509PublicKeyClass initialize is failing at runtime with WIN32: 13 ERROR_INVALID_DATA

I am trying to populate the CX509PublicKeyClass() object using InitializeFromEncodedPublicKeyInfo(data); where data is from the file id_rsa.pub (KeyFilePath) that I created using ss-keygen client in windows.
Sample code I am tying with
The image also shows the exception that is being thrown.
I suspect the issue could be with the expected encoding
public virtual void InitializeFromEncodedPublicKeyInfo(string strEncodedPublicKeyInfo, EncodingType Encoding = EncodingType.XCN_CRYPT_STRING_BASE64);
and I have tried multiple combinations, Hex and base64 , default string etc but I am still seeing the same error.
The answer lies in understanding RSA key formats
Private key contains: modulus, private exponent, public exponent, prime 1, prime 2, exponent 1, exponent 2 and coefficient
Public key contains: only modulus and public exponent.
PEM format produced by OpenSSL is actually base64 encoded and wrapped key data in the binary format called DER. Thus, to work with PEM format you must actually work with DER.
DER format is based on Abstract Syntax Notation One (ASN.1) standard. The standard specifies the encoding of tree-like data structures. Two predefined data structures are used for private and public RSA keys. Though I didn’t find a good parser for the format, with a couple of notes from the standard in hand I wrote a class for encoding and decoding ASN.1 values.
PEM format contains base64 encoded DER data. It also adds a header and footer to it. Below is an example of PEM file for a private key.

iOS AES256 decryption

I need to decrypt a string encrypted with AES256.
For example:
This is an encrypted string:
"U2FsdGVkX18egiyzJUY5gHS++2trNSYNSEXpJicKPBE="
using this key:
"70ca7c5b0f58ca290d39613fa3644251"
with the AES256 algorithm
The example string has been encrypted using:
https://code.google.com/p/crypto-js/
There are multiple tools that can be used to decrypt an AES256 encrypted string:
https://github.com/AlanQuatermain/aqtoolkit/tree/master/CommonCrypto
https://github.com/RNCryptor/RNCryptor
https://github.com/Gurpartap/AESCrypt-ObjC
I have tried them all but none of them was able to decrypt my string.
I'm sure it's encrypted correctly because I can decrypt it using this online tool:
http://www.appcove.com/tool/aes
Please help me.
Thank you,
George
-------------- EDIT --------------
Can you recommend a symmetric encryption/decryption algorithm for API(js)/iOS?
Something that you used to encrypt strings on the API and decrypt them on your iOS app.
Thank you
To get you started:
This is an encrypted string: "U2FsdGVkX18egiyzJUY5gHS++2trNSYNSEXpJicKPBE="
This is not an encrypted string. It is the Base64 rendering of an array of encrypted bytes. In order to decrypt it you first need to convert it from Base64 back into a byte array.
using this key: "70ca7c5b0f58ca290d39613fa3644251"
This is not a key. It is the hex string representation of the byte array which either is the actual key or can be used to derive the actual key. You need to convert it from a hex string back into a byte array.
with the AES256 algorithm
You need more information here: mode and padding at least.
What mode is being used? AES-ECB, AES-CBC, AES-CTR or some other mode? Look through the description to try and find out. The lack of an IV or a Nonce would probably indicate ECB mode, as Zaph's comment says. ECB mode is insecure, do not use it for any production code.
You also need to know what padding was used. Zaph says PKCS7 padding, which is very common, but the problem source should have told you that. You need to set the decryption method to expect the correct padding.
I'll give you a simple flow to show how AES works:
For the sake of clarity I'll use pseudo-objective-c to make it both understandable for you and fast for me.
// Here comes encryption process:
NSString *key = #"fsd7f897sfd8sfds…";
NSString *secretMessage = #"Confidential text";
AES *aes = [AES sharedAES];
NSString *encryptedMessage = [aes encryptWithKey:key message:secretMessage];
// Now is time for decryption:
Base64 *base64 = [Base64 sharedBase64];
NSString *messageToDecrypt = [base64 decode:encryptedMessage];
NSString *decryptedMesage = [aes decryptWithKey:key message:messageToDecrypt];
// Now you should have the result:
NSLog(decryptedMesage);
Take a look at http://travistidwell.com/jsencrypt/
From the google docs:
For the key, when you pass a string, it's treated as a passphrase and
used to derive an actual key and IV. Or you can pass a WordArray that
represents the actual key. If you pass the actual key, you must also
pass the actual IV.
For CryptoJS.AES.encrypt()
Is a string is passed in as the key another key will be derived and also an iv. This is going to be a compatibility problem because the method of actual key derivation would have to be know as well as the iv derivation and duplicated in iOS.
None of the above is a standard.
The solution is in JavaScript to pass in the key as a WordArray of the correct size (256 bits) and a WordArray iv.
Or per the docs:
"You can define your own formats in order to be compatible with other
crypto implementations. A format is an object with two
methods—stringify and parse—that converts between CipherParams objects
and ciphertext strings.
Then with these the same encryption/decryption can be matched in iOS.
Here is some information I figured out, this is WRT the encrypted data prior to base64 encoding:
The first 8 bytes are "Salted__" Probably used by the Javascript decryption to know the method to use.
The next 8 bytes are random. They are different for each encryption of the same data with same key They may be derived from the key with a random component.
The next bytes are in groups of 16 bytes (blocksize), just enough to contain the data + padding. Padding always adds at least one extra byte.
Because the iv is random the encrypted bytes will be different for each encryption with the same data and key but can be recovered by somehow using the key and leading bytes to re-generate the key and iv. The method is not secret, just unknown to me.
Of course this does not particularly help but does show the problem.

DCPcrypt encryption and hash algorithm used

I'm using the DCPcrypt library in Delphi 2007 for encrypting text for an in-house app.
I'm currently using the following code (not my actual key):
Cipher := TDCP_rijndael.Create(nil);
try
Cipher.InitStr('5t#ck0v3rf10w', TDCP_md5);
Result := Cipher.EncryptString('Test string');
finally
Cipher.Burn;
Cipher.Free;
end;
The comment for InitStr is:
Do key setup based on a hash of the key string
Will exchanging the MD5 algorithm for, say, SHA2-256 or SHA2-512 make any theoretical or actual difference to the strength of the encryption?
The direct answer to your question is 'No' - it won't make any appreciable difference to cryptographic strength. Yes, MD5 is broken, but really it's weakness does not make any difference in this particular application. AES has key sizes of 128, 192 and 256 bits. All you are doing here is creating a string pseudonym for a key (being either 16 bytes, 24 bytes or 32 bytes). When cryptographic experts say that a hash function is broken, what they mean by this is that given a known hash output, it is feasible to compute a message different from the original message, which also hashes to the same output. In other words, in order for the cryptographic strength or weakness of the hash function to have any meaning, the binary key must already be known to the malicious party, which means that it is only relevant when your security is already completely defeated.
The strength of the hashing algorithm is COMPLETELY irrelevant to the strength of the asymmetric cipher.
However...
However, of a much more serious concern is the lack of salting in your code. Unless you plan to manually salt your message (unlikely), your communications are very vulnerable to replay attack. This will be infinity worse if you use ECB mode, but without salting, it is a major security issue for any mode. 'Salting' means injecting a sufficiently large non-predictable non-repeating value in either the IV or at the head of the message before encryption.
This highlights a huge problem with DCPCrypt. Most users of DCPcrypt will not know enough about cryptography to appreciate the importance of proper salting, and will use the crypto component in exactly the way you have. When you use DCPcrypt in this way (which is very natural), DCPcrypt does NOT salt. In fact, it sets the IV to zero. And it gets worse... If you have chosen a key-streaming type of chaining mode (which is very popular), and your IV is habitually zero, your security will be completely and utterly broken if a single plaintext message is known or guessed, (OR even just a fragment of the message is guessed). DCPcrypt does offer an alternative way to initialize a binary key (not from string), together with allowing the user to set the IV (you must generate a random IV yourself). The next problem is that the whole IV management gets a bit complicated.
Disclosure
I am the author of TurboPower LockBox 3. Dave Barton's DCPcrypt, an admirable and comprehensive engineering work, was one of my inspirations for writing LockBox 3.
You should specify the type of attack on your encryption; suppose known-plaintext attack is used, and intruder uses precomputed hash values to find key string - then there should be no difference between the hash algorithms used, any hash algorithm will require nearly the same time to find key string.

2 Way Encryption Algorithm that for both Ruby & Node.JS that only encrypts to letters and numbers

I have a node.js server that will encrypt a string and store it into a database. I also have a RoR(Ruby on Rails) server that will retrieve the encrypted string from the database and decrypt it. The only criteria I have is that the encryption must only encrypt strings into a string of letters and numbers (no special characters)
Any suggestions
As others have suggested, a strong encryption like AES-CBC or AES-CTR together with Base-64 is one solution. Base-64 uses +, / and = in addition to the 62 alphanumeric characters. Hex (Base-16) is strictly alphanumeric, but takes more storage space. Base-32 only has the padding character, =, like Base-64. In a pinch it is possible to omit padding, and to recalculate in for decoding.
If you are wiling to accept a lower level of security then one alternative is to use a Vigenère cypher, where you can explicitly determine the input and output characters allowed.

simple text file encryption based on a key

I am trying to implement a simple text file encryption technique and I am using the following code to do so. The code is not written by me, I just googled and got it. The encryption technique seems to be pretty simple, concise and easy to implement. I see that it has only one function that can do the encryption and the decryption on the fly. Just pass the key it will do the trick. However, I just wanted to know, is it possible for me to check if the key is passed by the user is correct or not. Currently it will just encrypt / decrypt the text file based on the passed key. But there is no mechanism to check if we are decrypting with correct key or not. Whatever the key we pass, it will get decrypted, but it will not be readable. Any idea how to tackle this problem..?
procedure TEnDeCrypt.EnDecryptFile(pathin, pathout: string; Chave: Word);
var
InMS, OutMS: TMemoryStream;
cnt: Integer;
C: byte;
begin
InMS := TMemoryStream.Create;
OutMS := TMemoryStream.Create;
try
InMS.LoadFromFile(pathin);
InMS.Position := 0;
for cnt := 0 to InMS.Size - 1 DO
begin
InMS.Read(C, 1);
C := (C xor not (ord(chave shr cnt)));
OutMS.Write(C, 1);
end;
OutMS.SaveToFile(pathout);
finally
InMS.Free;
OutMS.Free;
end;
end;
Generate a checksum on the plain text using a hashing algorithm and store it at the beginning of the encrypted file.
You can verify the key by hashing the decrypted text and ensure that the checksum matches.
If you use a strong hashing algorithm such as SHA256 to generate the checksum, it will be difficult for the user to automate a brute force attack because it will be computationally expensive.
To ensure that the file is intact, you may also wish to store a checksum on the encrypted file and store it in the file header as well. Otherwise, there will be no way to differentiate an invalid password from a truncated file.
I typically use the Blowfish encryption algorithm, which is available for Delphi from multiple sources. Blowfish has no known weaknesses and is fairly compact and fast.
If you are aware of the kind of content your file will have (whether it is a binary file / text file etc), then you can sample the text and see if there are any non-ASCII or characters that are not expected in the file after decryption.
Another thing you can do is to add a watermark text at the end of the file. After decryption, you can check if your watermark is containing data that is outside the expected data-type (if you are expecting only characters and you see a non-char data in it, then there is possibly an issue). This though is not fool-proof, just a sort of a buffer for you.
That said, I will ask you this question - what is the intent behind this? The key the user is passing is to encrypt; so if the user is passing an invalid key, then they get invalid output. Why do you need to steer the user towards the right key? And if there is some business use-case for something like that, then you also need to understand that this is going to make your encryption very easy to break. I will suggest that you pick up a standard encryption algorithm and use that to encrypt your file.
The correct way to do what you are asking for is to Encrypt-then-Authenticate the data. There is some relevant discussion here: Should we MAC-then-encrypt or encrypt-then-MAC?
The conventional way is to first use a standard cipher in a standard mode, such as AES in CBC mode, and then calculate a HMAC (such as HMAC-SHA256) over the cipher text. There are also some cipher modes, such as CCM, EAX, GCM, that will perform both encryption and authentication.
Do not use a hash instead of a HMAC for this.
The key you use for encryption must be independent from the key you use for authentication. You could e.g. generate both randomly, but absolutely not using the System.Random function. If you are deploying to Vista SP2 or later, you could use CryptGenRandom from the Windows API, but otherwise you should use a cryptographic library with support for cryptographic random number generation.
If you use password based encryption, use a PBKDF2 implementation for deriving the encryption key and authentication key. There are four common ways to ensure the two keys are independent:
Use two separate Salt values;
Use a single salt but concatenate it with separate "labels", e.g. the strings 'E' and 'A' respectively,
Generate a twice as long derived key and use one half as encryption key and the other half as authentication key, or
Let the derived key be a "key encryption key" you use for encrypting randomly generated encryption keys and authentication keys.

Resources