Related
I'm trying to multiply all the values in integer array. The output of the given input array is expected to be a negative value but instead it returned as 0.
int[] nums = new int[] {41,65,14,80,20,10,55,58,24,56,28,86,96,10,3,84,4,41,13,32,42,43,83,78,82,70,15,-41};
Console.WriteLine(ArraySign(nums));
int ArraySign(int[] nums)
{
var value= nums.Aggregate(1, (x, y) => x * y); // returns 0
// var value= nums.Aggregate((x, y) => x * y); // returns 0
Console.WriteLine(value);
return value;
}
The result of multiplying the numbers in your array exceeds the limit of primitive numeric types like int and long. Consider using BigInteger Instead:
using System.Numerics; // Remember to add reference to "System.Numerics".
BigInteger[] nums = new BigInteger[] { 41, 65, 14, 80, 20, 10, 55, 58, 24, 56, 28, 86, 96, 10, 3, 84, 4, 41, 13, 32, 42, 43, 83, 78, 82, 70, 15, -41 };
BigInteger result = nums.Aggregate((x, y) => x * y);
Console.WriteLine(result); // -4198344456762767222202786622577049600000000
I have a file which has been encrypted by des.exe.
A file can be encrypted and decrypted using the following commands:
des -E -k "foo" sample.txt sample.txt.enc
des -D -k "foo" sample.txt.enc sample.txt.dec
I have attempted to decrypt using the following:
public byte[] Decrypt(FileInfo file, string key)
{
byte[] keyAsBytes = LibDesPasswordConvertor.PasswordToKey(key);
byte[] initializationVector = keyAsBytes;
var cryptoProvider = new DESCryptoServiceProvider();
cryptoProvider.Mode = CipherMode.CBC;
cryptoProvider.Padding = PaddingMode.None;
using (FileStream fs = file.OpenRead())
using (var memStream = new MemoryStream())
using (var decryptor = cryptoProvider.CreateDecryptor(keyAsBytes, initializationVector))
using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Write))
{
fs.CopyTo(cryptoStream);
fs.Flush();
cryptoStream.FlushFinalBlock();
return memStream.ToArray();
}
}
public static class LibDesPasswordConvertor
{
public static byte[] PasswordToKey(string password)
{
if (string.IsNullOrWhiteSpace(password))
{
throw new ArgumentException("password");
}
var key = new byte[8];
for (int i = 0; i < password.Length; i++)
{
var c = (int)password[i];
if ((i % 16) < 8)
{
key[i % 8] ^= (byte)(c << 1);
}
else
{
// reverse bits e.g. 11010010 -> 01001011
c = (((c << 4) & 0xf0) | ((c >> 4) & 0x0f));
c = (((c << 2) & 0xcc) | ((c >> 2) & 0x33));
c = (((c << 1) & 0xaa) | ((c >> 1) & 0x55));
key[7 - (i % 8)] ^= (byte)c;
}
}
AddOddParity(key);
var target = new byte[8];
var passwordBuffer = Encoding.ASCII.GetBytes(password).Concat(new byte[8]).Take(password.Length + (8 - (password.Length % 8)) % 8).ToArray();
using(var des = DES.Create())
using(var encryptor = des.CreateEncryptor(key, key))
{
for (int x = 0; x < passwordBuffer.Length / 8; ++x)
{
encryptor.TransformBlock(passwordBuffer, 8 * x, 8, target, 0);
}
}
AddOddParity(target);
return target;
}
private static void AddOddParity(byte[] buffer)
{
for (int i = 0; i < buffer.Length; ++i)
{
buffer[i] = _oddParityTable[buffer[i]];
}
}
private static byte[] _oddParityTable = {
1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14,
16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110,
112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127,
128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143,
145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158,
161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174,
176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191,
193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206,
208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223,
224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239,
241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254};
}
But when I execute:
const string KEY = "foo";
var utf8Bytes = Decrypt(new FileInfo(#"PATH-TO\sample.txt.enc"), KEY);
I get:
�1D���z+�a Sample.y���0F�01
Original text:
This is a Sample.
Encrypted:
ñGYjl¦ûg†¼64©‹Bø
é¯Kœ|
To my surprise you've already derived the key correctly. That was the meat of the problem, so Kudos for solving that part already. That the key is correct becomes clear when you see that part of the plaintext is present in the decryption - it wouldn't if the key was wrong.
Looking into the source and some docs from times past, I found a likely IV of all zeros instead of reusing the key bytes (both are very wrong, in cryptographic terms).
Furthermore, as always for SSLeay, the ECB and CBC modes use PKCS#7 compatible padding, rather than no padding.
Finally, FlushFinalBlock will be automatically called if you close the stream, e.g. by exiting the try-with-resources. So if you get the array afterwards then you should get the right values - after you unpad correctly, of course. If you call Flush then FlushFinalBlock will already be called, and calling it twice will make a mess out of things.
Simply removing the flush calls and retrieving the array after the CryptoStream is closed is the way to go.
Both DES and the key derivation (des_string_to_key and des_string_to_2keys) that Young copied from MIT are completely insecure. Using an all zero IV is wrong.
If you use this as transport mode than padding oracles will apply, and decryption is not even necessary for an attacker. The ciphertext is not integrity protected.
If you use the above routines to keep anything confidential or secure you're fooling yourself. This is 80s technology, and I think that real cryptographers wouldn't find it secure back then either.
Basically if your attacker is over 8 years old, you're in trouble.
I get a bit confused and frustrated when it comes to using NEST to querying, as it seems very hit and miss. I have no trouble querying when using standard JSON, so I was wondering if there was some way to query using a JSON object, I have code below
var query = "bkala";
var q = new
{
query = new
{
text = new
{
_all = "jane"
}
}
};
var qJson = JsonConvert.SerializeObject(q);
var hits = client.Search<Users>(qJson);
However, I get the error "Cannot convert from type string to System.Func, Nest.ISearchRequest"
If anyone knows how I can simply query using a JSON object, that would be fantastic, cheers in advance.
NEST and Elasticsearch.Net, the low level client that NEST uses under the covers, are flexible in how you wish to query. With NEST you have a couple of different ways:
NEST - High level client
1.Fluent API
var query = "bkala";
var searchResult = client.Search<MyDocument>(s => s
.Query(q => q
.Match(m => m
.Field("_all")
.Query(query)
)
)
);
Laid out as above, this API uses lambda expressions to define a fluent interface that mimics the structure of the Elasticsearch json API and query DSL.
2.Object Initializer Syntax
var query = "bkala";
var request = new SearchRequest<MyDocument>
{
Query = new MatchQuery
{
Field = "_all",
Query = query
}
};
var searchResult = client.Search<MyDocument>(request);
If lambda expressions are not your thing, then you can always define your searches using specific search types.
Elasticsearch.Net - Low level client
In cases where you would like to query with anonymous types (as per your question), json strings or a byte representation of a query, then you can use the low level client, Elasticsearch.Net, to achieve this. The low level client is exposed on the high level client through the .LowLevel property
1.Anonymous types
var query = new
{
query = new
{
match = new
{
_all = new
{
query = "bkala"
}
}
}
};
var searchResult = client.LowLevel.Search<SearchResponse<MyDocument>>(query);
Using the low level client on the high level client means that you can still take advantage of using Json.NET to deserialize search results; in this example, the search response can be accessed through searchResult.Body
2.Json string
var query = #"
{
""query"": {
""match"": {
""_all"": {
""query"": ""bkala""
}
}
}
}";
var searchResult = client.LowLevel.Search<SearchResponse<MyDocument>>(query);
3.Byte array
var bytes = new byte[] { 123, 13, 10, 32, 32, 34, 113, 117, 101, 114, 121, 34, 58, 32, 123, 13, 10, 32, 32, 32, 32, 34, 109, 97, 116, 99, 104, 34, 58, 32, 123, 13, 10, 32, 32, 32, 32, 32, 32, 34, 95, 97, 108, 108, 34, 58, 32, 123, 13, 10, 32, 32, 32, 32, 32, 32, 32, 32, 34, 113, 117, 101, 114, 121, 34, 58, 32, 34, 98, 107, 97, 108, 97, 34, 13, 10, 32, 32, 32, 32, 32, 32, 125, 13, 10, 32, 32, 32, 32, 125, 13, 10, 32, 32, 125, 13, 10, 125 };
var searchResult = client.LowLevel.Search<SearchResponse<MyDocument>>(bytes);
All of the above methods produce the following query
{
"query": {
"match": {
"_all": {
"query": "bkala"
}
}
}
}
Check out the Getting started guide on the github repo as well as the documentation on the Elastic website. We are continually working to improve documentation and PRs are more than welcome for areas where you feel we are lacking :)
I used this code from the web. But the result which is generated in c program did not match the c# encoding (ASCII, UTF-8 etc.,).
What is the best way to handle characters in c to overcome this?
This is for windows based exe.
For the text "Í£kúæ›Ì"
in VC I get Base64 Encoded string as "zaNr+uabzADMzMzMpGICvnj/GAA2IUEAAQAAAA=="
but in C# I get different results based on the encoding type
UTF-8 = > "K0FNMEFvdy1rK0FQb0E1aUE2QU13LQ=="
UTF-7 = > "w43Co2vDusOm4oC6w4w="
etc....
What encoding / no encoding in C# would get me the same result as the C Program.
#include <stdafx.h>
#include <locale.h>
#include "base64.h"
static const unsigned char pr2six[256] =
{
/* ASCII table */
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};
int Base64decode_len(const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
return nbytesdecoded + 1;
}
int Base64decode(char *bufplain, const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register unsigned char *bufout;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
bufout = (unsigned char *) bufplain;
bufin = (const unsigned char *) bufcoded;
while (nprbytes > 4) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
bufin += 4;
nprbytes -= 4;
}
/* Note: (nprbytes == 1) would be an error, so just ingore that case */
if (nprbytes > 1) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
}
if (nprbytes > 2) {
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
}
if (nprbytes > 3) {
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
}
*(bufout++) = '\0';
nbytesdecoded -= (4 - nprbytes) & 3;
return nbytesdecoded;
}
static const char basis_64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int Base64encode_len(int len)
{
return ((len + 2) / 3 * 4) + 1;
}
int Base64encode(char *encoded, const char *string, int len)
{
int i;
char *p;
p = encoded;
for (i = 0; i < len - 2; i += 3) {
*p++ = basis_64[(string[i] >> 2) & 0x3F];
*p++ = basis_64[((string[i] & 0x3) << 4) |
((int) (string[i + 1] & 0xF0) >> 4)];
*p++ = basis_64[((string[i + 1] & 0xF) << 2) |
((int) (string[i + 2] & 0xC0) >> 6)];
*p++ = basis_64[string[i + 2] & 0x3F];
}
if (i < len) {
*p++ = basis_64[(string[i] >> 2) & 0x3F];
if (i == (len - 1)) {
*p++ = basis_64[((string[i] & 0x3) << 4)];
*p++ = '=';
}
else {
*p++ = basis_64[((string[i] & 0x3) << 4) |
((int) (string[i + 1] & 0xF0) >> 4)];
*p++ = basis_64[((string[i + 1] & 0xF) << 2)];
}
*p++ = '=';
}
*p++ = '\0';
return p - encoded;
}
int main() {
char mysrc[] = "Hello world...";
char mysrc[] = "Í£kúæ›Ì";
char myb64[1024] = "";
char mydst[1024] = "";
//Base64encode(myb64, mysrc, 28);
Base64encode(myb64, mysrc, strlen(mysrc); //corrected
printf("The string\n[%s]\nencodes into base64 as:\n[%s]\n", mysrc, myb64);
printf("\n");
Base64decode(mydst, myb64);
printf("The string\n[%s]\ndecodes from base64 as:\n[%s]\n", myb64, mydst);
return 0;
}
You could try with the Encoding.GetEncoding("ISO-8859-1"), so
Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
string base64Encoded = Convert.ToBase64String(encoding.GetBytes("Í£kúæ›Ì"));
Note that in general yours is a very complex question... See for example https://gcc.gnu.org/onlinedocs/cpp/Character-sets.html the page of gcc about the encoding of source files.
Note that this response is in general wrong... because the problem is quite complex. A char* in C/C++ is more similar to an unencoded byte array than to a string.
A string constant contained in a C source file (a "something") is a byte array encoded in the encoding of the source file. In Visual Studio you can select it by doing File->SaveAs, then clicking on the little arrow of the Save button, Save With Encoding. For example:
printf("%d", strlen("è"));
will print 1 if the encoding of the file is Windows-1252, 2 if the encoding of the file is utf-8.
So if you want to encode in the same way in C#, you have to do Encoding.GetEncoding("encodingName") (or Encoding.UTF8 if the C/C++ file was UTF8 encoded)
but this is only for string constants!
If for example you do a scanf("%s", str) (so you accept a string from the console), the encoding of the bytes in the str will be the encoding of the console. If you take a string from a windows control, then the encoding will be the default encoding of Windows (so Encoding.Default in C#). If you read an external file, then the char* will be the bytes of the file, so the encoding of the char* will be the encoding of the file.
Encode
string base64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("my string"));
// base64Encoded = "bXkgc3RyaW5n"
Decode
string base64Decoded = Encoding.UTF8.GetString(Convert.FromBase64String(base64Encoded));
// base64Decoded = "my string"
I read about conversion of ASCII to EBCDIC using this link;
Convert String from ASCII to EBCDIC in Java?
But this is in java. My requirement is in C#.Net.
So can you please help me with this?
Thanks & Regards,
Krishna Kumar
Here's an implementation (by #Jon Skeet) you might find useful.
I tried the above code, and found it did not work for me.
For example, '04' (0x3034) ascii translated to 0x00f000f4 ebcdic. Problem seemed to be the encoding.
Played with several approches to change this, but finally found the best solution was the most basic. Instead of using Convert.ToChar, I plugged the hex value into the array.
Please see following:
static byte[] ASCIItoEBCDIC(string asciiString)
{
byte[] asciiToEbcdicTable = new byte[256] {
0x00,0x01,0x02,0x03,0x37,0x2D,0x2E,0x2F,0x16,0x05,0x25,0x0B,0x0C,0x0D,0x0E,0x0F,
0x10,0x11,0x12,0x13,0x3C,0x3D,0x32,0x26,0x18,0x19,0x3F,0x27,0x1C,0x1D,0x1E,0x1F,
0x40,0x5A,0x7F,0x7B,0x5B,0x6C,0x50,0x7D,0x4D,0x5D,0x5C,0x4E,0x6B,0x60,0x4B,0x61,
0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0x7A,0x5E,0x4C,0x7E,0x6E,0x6F,
0x7C,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,
0xD7,0xD8,0xD9,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xBA,0xE0,0xBB,0xB0,0x6D,
0x79,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x91,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xC0,0x4F,0xD0,0xA1,0x07,
0x20,0x21,0x22,0x23,0x24,0x15,0x06,0x17,0x28,0x29,0x2A,0x2B,0x2C,0x09,0x0A,0x1B,
0x30,0x31,0x1A,0x33,0x34,0x35,0x36,0x08,0x38,0x39,0x3A,0x3B,0x04,0x14,0x3E,0xFF,
0x41,0xAA,0x4A,0xB1,0x9F,0xB2,0x6A,0xB5,0xBD,0xB4,0x9A,0x8A,0x5F,0xCA,0xAF,0xBC,
0x90,0x8F,0xEA,0xFA,0xBE,0xA0,0xB6,0xB3,0x9D,0xDA,0x9B,0x8B,0xB7,0xB8,0xB9,0xAB,
0x64,0x65,0x62,0x66,0x63,0x67,0x9E,0x68,0x74,0x71,0x72,0x73,0x78,0x75,0x76,0x77,
0xAC,0x69,0xED,0xEE,0xEB,0xEF,0xEC,0xBF,0x80,0xFD,0xFE,0xFB,0xFC,0xAD,0xAE,0x59,
0x44,0x45,0x42,0x46,0x43,0x47,0x9C,0x48,0x54,0x51,0x52,0x53,0x58,0x55,0x56,0x57,
0x8C,0x49,0xCD,0xCE,0xCB,0xCF,0xCC,0xE1,0x70,0xDD,0xDE,0xDB,0xDC,0x8D,0x8E,0xDF};
byte[] ebcdicBinary = new byte[asciiString.Length];
for (int pos = 0; pos < asciiString.Length; ++pos)
{
int ebcdicIndex = asciiString[pos];
ebcdicBinary[pos] = asciiToEbcdicTable[ebcdicIndex];
}
return ebcdicBinary;
}
Try like below code
public string ConvertASCIItoEBCDIC(string strASCIIString)
{
int[] a2e = new int[256]{
0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15,
16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31,
64, 79,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97,
240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111,
124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214,
215,216,217,226,227,228,229,230,231,232,233, 74,224, 90, 95,109,
121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150,
151,152,153,162,163,164,165,166,167,168,169,192,106,208,161, 7,
32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27,
48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62,225,
65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87,
88, 89, 98, 99,100,101,102,103,104,105,112,113,114,115,116,117,
118,119,120,128,138,139,140,141,142,143,144,154,155,156,157,158,
159,160,170,171,172,173,174,175,176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,202,203,204,205,206,207,218,219,
220,221,222,223,234,235,236,237,238,239,250,251,252,253,254,255
};
char chrItem = Convert.ToChar("0");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strASCIIString.Length; i++)
{
try
{
chrItem = Convert.ToChar(strASCIIString.Substring(i, 1));
sb.Append(Convert.ToChar(a2e[(int)chrItem]));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return string.Empty;
}
}
string result = sb.ToString();
sb = null;
return result;
}
and check the saple code on these links
http://kseesharp.blogspot.com/2007/12/convert-ascii-to-ebcdic.html
http://forums.asp.net/t/167516.aspx
http://www.yoda.arachsys.com/csharp/ebcdic/
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/c2b074fd-4293-4bf4-b7fa-1803fc625d43