Generating a key - vb.net

I am writing an encryption application that requires a 64 bit key. I am currently using the following code to automatically generate a key.
Function GenerateKey() As String
' Create an instance of a symmetric algorithm. The key and the IV are generated automatically.
Dim desCrypto As DESCryptoServiceProvider = DESCryptoServiceProvider.Create()
' Use the automatically generated key for encryption.
Return ASCIIEncoding.ASCII.GetString(desCrypto.Key)
End Function
I am wanting the user to create their own key. Can I convert a user defined password (a string) into a 64 bit key that can be used?

The answer depends on how secure you want it to be, I'm no security expert so I wouldn't give advice on it.
I did see this though: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx It can be used to derives bytes from a string key and salt in the way Jodrell eluded to, and would be far better than rolling yor own.
The other constructor that might be suited after that stage is detailed here: http://msdn.microsoft.com/en-us/library/51cy2e75.aspx
I'm sure if you searched for that on the web you could find examples of how to use it.

Related

Creating a Private Key from a String

Use case
We have an app, where a user puts in a private key into a text box and then we save that. We then want to use that string value to create a private key to be able to sign stuff with it.
Ruby example
In Ruby this is done with something like this:
OpenSSL::Key::RSA.new(string_key_value_here)
I know that you can use Erlang's crypto module in Elixir and I thought that the function generate_key/2 could be used here. On further review I don't think that it'll work as the second parameters that it wants for that function are:
{ModulusSizeInBits::integer(), PublicExponent::key_value()}
Is it possible to do something like this with Elixir / Erlang?

Attempt retrieval of value from VBA dictionary and raise error if key not in use?

I've used dictionaries (Whether they were called that or not) in a number of other languages, but there's always been a method that can be called with on parameter that either:
A) Returns the associated value if the parameter is in use as a key, or
B) Indicates in some way that the parameter is not used as a key
I've been forced into a position where I have to learn excel/VBA and used the collections class for all of about five minutes before the lack of an .exists method led me to look for something else. The general consensus seems to be that the scripting.Dictionary class is the VBA equivalent of associative arrays/dictionaries/hashtables in other languages.
The one thing I don't like the look of though is that the only way I can see of retrieving the value associated with a given key is to use the .items property (either explicitly, or via scripting.Dictionary("key")). But rather than doing anything to indicate the issue if key is not in use in the dictionary, it adds it.
I know I can use a if structure with .exists being the test to achieve the same functionality, and can write my own function that raises an error if the exists test fails, but it seems a lot of stuffing around to achieve what is core functionality in Python (raises KeyError), PHP (raises a Notice), Java (Maps return null - although that is not necessarily ideal in the case of HashMaps where null actually is a valid value - but it does work as an indicator for HashTables).
So is there any way of attempting to retrieve a value by key that will do something (ideally throw an error) if the key is not in use, rather than silently adding it? Google hasn't provided any answers - but maybe I'm just not phrasing the search well.
I find it inconvenient too that Dictionary adds the key when you access a non-existing key.
Just use Collection and write the missing Exist function yourself, e.g.
Function ExistsInCollection(ByVal c As Collection, ByVal key As Variant) As Boolean
On Error GoTo not_exists
c.Item key
ExistsInCollection = True
not_exists:
End Function

How can I produce a valid Private Key (in any format) from the primes?

I have the necessary components to build the private/public RSA key: N, E, D, P, & Q. I can derive the other values for the CRT if needed. How can I use these parameters to produce a valid Private/Public key in DER, PEM, or PKCS#7? It doesn't matter which to me as I can convert between them. I'm looking for a tool, library, script, or program that supports assigning these values and writing out a valid file, so I don't have to read hundreds of pages on ASN.1. Every tool I've looked at doesn't expose this use case in the API.
If you are using Java, there is the RSAPrivateKeySpec class, which takes BigInteger arguments of modulus and exponent. There are subclasses which take instead of N the P and Q primes (for more efficiency). You can then use a KeyFactory to convert this object to a Key, and then to some EncodedKeySpec class like PKCS8EncodedKeySpec or X509EncodedKeySpec.
You should be able to use OpenSSL (the library).
BIGNUM is described here. There are many functions to create a BIGNUM out of your input (depending on format). BN_bin2bn is probably the simplest, but hexadecimal or decimal input is also supported.
RSA is a structure that contains BIGNUMs. It's described here. You can initialise it yourself (directly).
You can then write the RSA structure using one of the PEM functions (described here). For example, PEM_write_RSAPrivateKey writes a PEM file containing a private key (you can also encrypt it, if you want to).
I'm not aware of any tool that does all of the above. Also, ASN.1 isn't so bad (a public/private key is pretty much a SEQUENCE of INTEGERs).

Occasional bad data error when decrypting

I have a very strange situation.
Basically I have code that uses a decryptor created by:
Dim des3 As New TripleDESCryptoServiceProvider
des3.Mode = CipherMode.CBC
Return des3.CreateDecryptor(_encKey, _initVec)
The _encKey and _initVec are hardcoded.
I use it by calling:
Dim res() As Byte = decrypt(Convert.FromBase64String(_data))
m_transformDec.TransformFinalBlock(res, 0, res.Length)
Here _data is a string containing the encrypted value. m_transformDec is the Decryptor created previously.
Usually this works. Occasionally, I get a "bad data" error. I print out the value of _data, and it is always the same.
The code is multithreaded, which I suspect is the reason for both the problem, and it being hard to reproduce. The decryptor is created in the creation of the class, and the decryption is done in a Shared function, but I don't see anything there which is not thread-safe.
Any ideas?
You should not assume anything is safe for concurrent calls unless you have reason to believe it is. In the docs, you have the boilerplate text that instance members are not guaranteed to be thread-safe, so you should defensively lock the des3 object when you're using it.
You should not be hard coding the initialization vector; it should be randomly chosen when encrypting data, then stored in some way with the encrypted data (many people choose to tack it onto the beginning of the data, then remove it and use it for decryption; use whatever storage scheme you prefer, though). Using the same IV defeats the purpose of the IV, which serves to make plaintext attacks more difficult.

Is there anything like SHA1CryptoServiceProvider (Which is C#) in Objective-C?

I am trying to create a serial number checker in an app that I am writing, and it uses cryptography to encode the name and entered number against what it actually should be. I am familiar with the SHA1CryptoServiceProvider used in C#, but is there anything like this in Objective-C?
Here is sample code from C# that I want to convert to Objective-C:
string license = txtnLicense.Text;
SHA1CryptoServiceProvider provider = new SHA1CryptoServiceProvider();
string finalLicense = BitConverter.ToString(provider.ComputeHash(bytes));
bool isGood = (BitConverter.ToString(provider.ComputeHash(bytes)).Replace("-", "") == license.Replace("-", ""));
Mac OS X comes with an easy-to-use encryption and hashing library built-in called CommonCrypto. You don't have to link against anything special to use it. See the headers in /usr/include/CommonCrypto for its interface and CC_SHA1(3cc) for docs.
using openssl for license keys shows how to use SHA1. It may be a good start.