php memcached enyim client flag problem - c#

I am trying to use memcached with both a php (memcached) and C# (enyim) client.
I have a scenario where I want to CAS a value in php. To do this I am using the following code:
$memcached = new Memcached;
$memcached->addServer('localhost', 11211) or die ("Could not connect");
$memcached->setOption(Memcached::OPT_COMPRESSION, false); // the enyim client doesn't support compression
do {
$entries = $memcached->get($theKey, null, $cas);
if ($memcached->getResultCode() == Memcached::RES_NOTFOUND) {
$entry = somearray("foo");
$memcached->add($theKey, $entry);
} else {
$entries[] = "bar";
$memcached->cas($cas, $theKey, $entries);
}
}
while ($memcached->getResultCode() != Memcached::RES_SUCCESS AND $memcached->getResultCode() != Memcached::RES_END);
This works all well and fine to begin with.
But then, when the C# client CAS's the same value it goes wrong.
Php gives a warning at:
$entries = $memcached->get($theKey, null, $cas);
namely that:
PHP Warning: Memcached::get(): could not uncompress value in ... at line ...
And as a result an infinite loop occurs.
Now I tried to get the key from the memcached server via telnet and the data was right there.
In php I am also able to SET to this key without a problem.
I noticed one thing: after the php client has SET something, the flag was 0.
Now after the C# client has CAS'd the value, the flag was 274.
Is there some flag collision on the php lib going on? Or is it something else?
If anyone can help me resolve this problem I'd be gratefull!
lordstyx
[EDIT]
Well then. Since this question isn't getting an answer let me put it differently.
Is there a way to stop the C# client from setting flag 274?

So I eventually found an answer to my problem. It might not help all of you, because I switched from the Enyim to the BeIT memcached client (http://code.google.com/p/beitmemcached/)
Now to make the BeIT client compatible with the php client you have to change Serializer.cs
In the enum SerializedType I changed the number of "String" to 0 and ByteArray to 2, which gave this:
internal enum SerializedType : ushort
{
ByteArray = 2,
Object = 1,
String = 0, //mod: turned around the numbers for String and ByteArray so it is compatible with php client
Datetime = 3,
....
I believe I went with BeIT because I couldn't find or figure out how the flags worked in the Enyim client. If you understand how it work though, I'm sure that you can change that client in a same manner

If I am not wrong, mixing languages/platforms with memcached is a bad idea. See another question on similar topic.

For the record. Since the library is open source, then its possible to modify.
In the class Enyim.Caching.Memcached.DefaultTranscoder, change the function
public static uint TypeCodeToFlag(TypeCode code)
{
return (uint)((int)code | 0x0100);
}
to
public static uint TypeCodeToFlag(TypeCode code)
{
if (code == TypeCode.String)
{
return 0;
}
return (uint)((int)code | 0x0100);
}
274 = TypeCode.String | 0x0100
Since i don't know the memcache protocol then i don't know whats doing. However, php's memcache requires 0, so i set to zero when the variable defined is a string.
ps: beitmemcached hasn't be updated for a long while.

Related

Encrypting BIG emails in Outlook cause Low Ressources Exception in C#

I am developing a tool, that encrypts emails with S/MIME in bulk within Outlook 2013. It works so far, but when I am trying to encrypt a REALLY BIG email (in the test case it was about 60MB raw). I get a COMException stating unsufficient ressources.
I can go around this, by working direktly with EWS and MimeKit (which works like a charm! Thank you #jstedfast), but I'd like to find a way to work in Outlook, for network traffic considerations. I know these changes will be synched to Exchange eventually, but during the process itself, it is independent of bandwidth.
I am also looking at MapiEx, but if there is an easier solution, than having yet another dependency (and with MFC too), I'd be happy! Maybe there are some settings, I'd have to make before.
A bit of code. The Exception it caught somewhere else.
public void String SetEncryption(MailItem mailItem)
{
PropertyAccessor pa = null;
try
{
pa = mailItem.PropertyAccessor;
Int32 prop = (int)pa.GetProperty(_PR_SECURITY_FLAGS);
Int32 newprop = prop | 1;
pa.SetProperty(_PR_SECURITY_FLAGS, newprop);
}
finally
{
Marshal.FinalReleaseComObject(pa);
pa = null;
}
}
Edit: The Exception is not coming, when the encryption is set, but when the result is saved, after the encryption is set.
SetEncryption(mailItem);
mailItem.Save();
I solved it myself.
Since I had the problems in Outlook itself, I was trying MAPIEx to access the raw S/MIME Attachment in the email and de-/encrypt it using MimeKit/BouncyCastle.
The same problem occoured, but with a different error message, which lead me to the following site: ASN.1 value too large.
To sum it up: The Crypto API has two signatures. One which takes a byte array and one, which takes a stream. The first one has an arbitrary imposed (!!!) limit of 100 Million Bytes. Since the enveloped CMS has double base64 the ratio of this 100 MB is 9/16, which is round about 56 MB.
I assume, that Outlook uses the same API-Call and therefore has this limit.
I know it is not a fact, but the evidence strongly supports this theory. :)
Check if KB 2480994 is installed: http://support.microsoft.com/kb/2480994

C# 3DES encryption to C decryption

I have created a C# assembly that does 3DES encryption/encryption and tested it. I now need to decrypt the data on a remote machine for an install. .NET is not guaranteed to be present when my native process runs, so I need to decrypt it using Win32 C++ methods. This is for a commercial applicaiton, so third party libraries are going to need to flexible with their licensing. I would prefer a simple example to get me started. Most of the examples I have found so far require importing session keys. I'm not using those. I am encrypting on machineA with .NET 2.0, and passing over to machineB where I will retrive the key and decrypt with native Win32 API's. Can anyone point me in the right direction with some examples?
I know I need to start with CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT).
However, the next step appears to be import key and it looks like it requires (http://support.microsoft.com/kb/228786). Is this correct, or am I making this too difficult. I have a basic understanding of encryption. Thanks in advance!
Take a look to the following code:
#define TRIPLEDES_KEYSIZE 24
#define TRIPLEDES_BLOCKSIZE 8
...
BYTE key[TRIPLEDES_KEYSIZE] = { ... };
...
HCRYPTKEY hKey;
typedef struct
{
BLOBHEADER hdr;
DWORD cbKeySize;
BYTE rgbKeyData [TRIPLEDES_KEYSIZE];
} KEYBLOB;
KEYBLOB keyBlob;
memset(&keyBlob, 0, sizeof(keyBlob));
keyBlob.cbKeySize = TRIPLEDES_KEYSIZE;
keyBlob.hdr.bType = PLAINTEXTKEYBLOB;
keyBlob.hdr.bVersion = CUR_BLOB_VERSION;
keyBlob.hdr.aiKeyAlg = CALG_3DES;
memcpy(keyBlob.rgbKeyData, key, TRIPLEDES_KEYSIZE);
BOOL res = CryptImportKey(hCryptProv, (const BYTE*)&keyBlob, sizeof(keyBlob), 0, 0, &hKey);
if (res)
{
res = CryptSetKeyParam(hKey, KP_MODE, CRYPT_MODE_ECB, 0);
Please note you can use CRYPT_MODE_ECB or CRYPT_MODE_CBC in the call to the function CryptSetKeyParam with KP_MODE option depending on what you want to do. You can set an IV by for example the following code
res = CryptSetKeyParam(hKey, KP_IV, iv, 0);
which makes only sense in a CRYPT_MODE_CBC like mode.
Please note there is also a different 3DES mode (CALG_3DES_112) working with only 112 Bit key (i.e. with two normal DES keys). You have to modify the code if you want to use this mode.
Edit:
You should write some classes in C++ to manage all things of the CryptoApi. It will save you a lot of headache.

HASP HL working demo needed for C#

Okay. Well, I know this question has a good chance of being closed within the first 10 minutes, but I am going to ask it anyways for I have spent almost day and an half trying to find a solution. Still, I can't figure this one out. There is not much info on this on the Internet not even on the HASP (safenet) website although they have demos.
I have a HASP HL USB dongle. I try to convert their demo and test run it but for the life of me I simply can't get it to login even. It keeps raising Aladdin.HASP.HaspStatus.HaspDotNetDllBroken exception.
However, if I run the C version of their demo, it works perfectly.
Here is the Csharp version of my code:
Aladdin.HASP;
HASP myHasp = new HASP();
var thestatus = myHasp.Login(vender_code);
myHasp.Logout;
I would like to login to USB HASP and get its HaspID and the settings in its memory.
Thanks in advance,
It might be that you aren't having all dependencies for the HASP runtime. I'm packing with the app:
hasp_windows_NNNNN.dll (NNNNN = your number)
hasp_net_windows.dll
MSVCR71.DLL (added manually)
msvc runtime 80
One runtime library is required by HASP and it doesn't tell you which one unless you put it in the DEPENDS.EXE utility (you probably have you on your Visual Studio installation).
To log in (and read some bytes):
byte[] key = new byte[16];
HaspFeature feature = HaspFeature.FromFeature(4);
string vendorCode = "your vendor string, get it from your tools";
Hasp hasp = new Hasp(feature);
HaspStatus status = hasp.Login(vendorCode);
if (HaspStatus.StatusOk != status)
{
// no license to run
return false;
}
else
{
// read some memory here
HaspFile mem = hasp.GetFile(HaspFileId.ReadOnly);
mem.Read(key, 0, 16);
status = hasp.Logout();
if (HaspStatus.StatusOk != status)
{
//handle error
}
}
Hope it helps. My HASPed software works like a charm. BTW, wasn't able to put envelope around .NET app under no combination of settings.

Why do I get Ice::MemoryLimitException, even with Ice.MessageSizeMax=2000000

Hi I have written a C# client/server application using the Zeroc Ice communication libary (v3.4.2).
I am transferring a sequence of objects from the server which are then displaying them in the client in a tabular format. Simple enough.
I defined following slice types
enum DrawType { All, Instant, Raffle };
struct TicketSoldSummary {
int scheduleId;
DrawType dType;
string drawName;
long startDate;
long endDate;
string winningNumbers;
int numTicket;
string status;
};
sequence<TicketSoldSummary> TicketSoldSummaryList;
interface IReportManager {
[..]
TicketSoldSummaryList getTicketSoldSummary(long startTime, long endTime);
};
When I call this method it usually works fine, but occasionally (approx 25% of the time) the caller gets a Ice::MemoryLimitException. We are usually running 2-3 clients at a time.
I searched on the Internet for answers and I was told to increase Ice.MessageSizeMax, which I did. I have increased MessageSizeMax right up to 2,000,000 Kb, but it made no difference, I just did a test with 31,000 records (approximately 1.8 Megs of data) and still get Ice.MemoryLimitException. 1.8 Megs is not very big!
Am I doing something wrong or is there a bug in Zeroc Ice?
Thanks so much to anyone that can offer some help.
I believe MessageSizeMax needs to be configured on the client as well as the server side. Also have tracing enabled with max value (3) and check the size of the messages (on the wire)
Turn on Ice.Warn.Connections on the server side and see the logs. Also make sure the client max message size gets applied correctly. I set Ice.MessageSizeMax on the client as below,
Ice.Properties properties = Ice.Util.createProperties();
properties.setProperty("Ice.MessageSizeMax", "2097152");//2gb in kb
Ice.InitializationData initData = new Ice.InitializationData();
initData.properties = properties;
Ice.Communicator communicator = Ice.Util.initialize(initData);

How can I port a Javascript AES library to .NET to ensure interoperability?

Background:
I have data that I'm encrypting with javascript on the client side that needs to be decrypted on the server side.
As far as I can tell, the javascript AES library I'm using does not interop with the C# Rijndael library.
Thus, I'm left to essentially implement the javascript AES in C# for use.
I'm going to try to compile the javascript using jsc.exe into a dll and see if reflector can save me some time.
I'm aware that jscript is not the same as javascript, but I'm hoping I can get away with something that works awefully close, and just do the touchups manually.
Problem:
When I compile the javascript using JSC I get the following error:
error JS1234: Only type and package
definitions are allowed inside a
library
The offending line is this first line in the following lines of code:
var GibberishAES = (function(){
var Nr = 14,
/* Default to 256 Bit Encryption */
Nk = 8,
Decrypt = false,
enc_utf8 = function(s)
{
try {
return unescape(encodeURIComponent(s));
}
catch(e) {
throw 'Error on UTF-8 encode';
}
},
dec_utf8 = function(s)
{
try {
return decodeURIComponent(escape(s));
}
catch(e) {
throw ('Bad Key');
}
},
And the full source can be found here:
I'm not sure what the problem is. I'm also open to suggestions as to how to encrypt/decrypt data between Javascript and C#.
If you just want to do AES from Javascript, did you try slowAES? It worked for me.. I found good interop between slowAES and the built-in Rijndael or AES classes in .NET. Also I found that the class design was natural and easy to use and understand. This would not require porting from Javascript to JScript.
Password-based-Key-derivation is not really handled by SlowAES. If you need that (likely) then I suggest the PBKDF2 implementation from Parvez Anandam. I also have used that, and it works nicely.
When I tested slowAES coupled with Anandam's PBKDF2, it had good interop with C#'s RijndaelManaged class, in CBC mode.
Don't be put off by the name "slowAES" - it isn't really slow. It's named "slow" because it's Javascript.
If you cannot use something that is clean and compatible like slowAES, then before trying the jsc compiler, I would suggest packaging the existing javascript code into a Windows Script Component. The WSC allows you to package script logic as a COM component, where it becomes usable by any COM-capable environment including any .NET application. Here's a post that shows how to package slowAES as a WSC.
For some reason not many people are aware that you can package script code as a COM component, but it's been around for 10 years. It may sound unusual to you, but it beats doing the port. The code inside the WSC is Javascript, not Javascript.NET.
I had this problem today as well. I happen to stumble upon the solution. use package theNameSpace { class Whatever { function func() { return "the results"; } } }

Categories

Resources