How do I use BER encoding with object System.DirectoryServices.Protocols.BerConverter.Encode("???", myData) - encoding

I need to encode and decode BER data. .NET has the class System.DirectoryServices.Protocols.BerConverter
The static method requires me to enter a string in the first parameter as shown below
byte[] oid = { 0x30, 0xD, 0x6, 0x9, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0 }; // Object ID for RSA
var result2 = System.DirectoryServices.Protocols.BerConverter.Decoding("?what goes here?", oid);
BER encoding is used in LDAP, Certificates, and is commonplace in many other formats.
I'll be happy with information telling me how to Encode or Decode on this class. There is nothing on Stack Overflow or the first few pages of Google (or Bing) regarding this.
Question
How do I convert the byte array above to the corresponding OID using BER decoding?
How can I parse (or attempt to parse) SubjectPublicKeyInfo ASN.1 data in DER or BER format?
It seems the DER encoding\decoding classes are internal to the .NET framework. If so, where are they? (I'd like to ask connect.microsoft.com to make these members public)

How do I convert the byte array above to the corresponding OID using BER decoding?
After you have extracted the OID byte array, you can convert it to an OID string using OidByteArrayToString(). I have included the code below, since I couldn't find a similar function in the .NET libraries.
How can I parse (or attempt to parse) SubjectPublicKeyInfo ASN.1 data in DER or BER format?
I was not able to find a TLV parser in the .NET SDK either. Below is an implementation of a BER TLV parser, BerTlv. Since DER is a subset of BER, parsing will work the same way. Given a BER-TLV byte[] array, it will return a list of BerTlv objects that support access of sub TLVs.
It seems the DER encoding\decoding classes are internal to the .NET framework. If so, where are they? (I'd like to ask connect.microsoft.com to make these members public)
Maybe somebody else can answer this question.
Summary
Here is an example of how you can use the code provided below. I have used the public key data you provided in your previous post. The BerTlv should probably be augmented to support querying like BerTlv.getValue(rootTlvs, '/30/30/06');.
public static void Main(string[] args)
{
string pubkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDrEee0Ri4Juz+QfiWYui/E9UGSXau/2P8LjnTD8V4Unn+2FAZVGE3kL23bzeoULYv4PeleB3gfmJiDJOKU3Ns5L4KJAUUHjFwDebt0NP+sBK0VKeTATL2Yr/S3bT/xhy+1xtj4RkdV7fVxTn56Lb4udUnwuxK4V5b5PdOKj/+XcwIDAQAB";
byte[] pubkeyByteArray = Convert.FromBase64String(pubkey);
List<BerTlv> rootTlvs = BerTlv.parseTlv(pubkeyByteArray);
BerTlv firstTlv = rootTlvs.Where(tlv => tlv.Tag == 0x30).First();//first sequence (tag 30)
BerTlv secondTlv = firstTlv.SubTlv.Where(tlv => tlv.Tag == 0x30).First();//second sequence (tag 30)
BerTlv oid = secondTlv.SubTlv.Where(tlv => tlv.Tag == 0x06).First();//OID tag (tag 30)
string strOid = OidByteArrayToString(oid.Value);
Console.WriteLine(strOid);
}
Output:
1.2.840.113549.1.1.1
OID Encode/Decode
public static byte[] OidStringToByteArray(string oid)
{
string[] split = oid.Split('.');
List<byte> retVal = new List<byte>();
//root arc
if (split.Length > 0)
retVal.Add((byte)(Convert.ToInt32(split[0])*40));
//first arc
if (split.Length > 1)
retVal[0] += Convert.ToByte(split[1]);
//subsequent arcs
for (int i = 2; i < split.Length; i++)
{
int arc_value = Convert.ToInt32(split[i]);
Stack<byte> bytes = new Stack<byte>();
while (arc_value != 0)
{
byte val = (byte) ((arc_value & 0x7F) | (bytes.Count == 0 ? 0x0:0x80));
arc_value >>= 7;
bytes.Push(val);
}
retVal.AddRange(bytes);
}
return retVal.ToArray();
}
public static string OidByteArrayToString(byte[] oid)
{
StringBuilder retVal = new StringBuilder();
//first byte
if (oid.Length > 0)
retVal.Append(String.Format("{0}.{1}", oid[0] / 40, oid[0] % 40));
// subsequent bytes
int current_arc = 0;
for (int i = 1; i < oid.Length; i++)
{
current_arc = (current_arc <<= 7) | oid[i] & 0x7F;
//check if last byte of arc value
if ((oid[i] & 0x80) == 0)
{
retVal.Append('.');
retVal.Append(Convert.ToString(current_arc));
current_arc = 0;
}
}
return retVal.ToString();
}
BER-TLV Parser
class BerTlv
{
private int tag;
private int length;
private int valueOffset;
private byte[] rawData;
private List<BerTlv> subTlv;
private BerTlv(int tag, int length, int valueOffset, byte[] rawData)
{
this.tag = tag;
this.length = length;
this.valueOffset = valueOffset;
this.rawData = rawData;
this.subTlv = new List<BerTlv>();
}
public int Tag
{
get { return tag; }
}
public byte[] RawData
{
get { return rawData; }
}
public byte[] Value
{
get
{
byte[] result = new byte[length];
Array.Copy(rawData, valueOffset, result, 0, length);
return result;
}
}
public List<BerTlv> SubTlv
{
get { return subTlv; }
}
public static List<BerTlv> parseTlv(byte[] rawTlv)
{
List<BerTlv> result = new List<BerTlv>();
parseTlv(rawTlv, result);
return result;
}
private static void parseTlv(byte[] rawTlv, List<BerTlv> result)
{
for (int i = 0, start=0; i < rawTlv.Length; start=i)
{
//parse Tag
bool constructed_tlv = (rawTlv[i] & 0x20) != 0;
bool more_bytes = (rawTlv[i] & 0x1F) == 0x1F;
while (more_bytes && (rawTlv[++i] & 0x80) != 0) ;
i++;
int tag = Util.getInt(rawTlv, start, i-start);
//parse Length
bool multiByte_Length = (rawTlv[i] & 0x80) != 0;
int length = multiByte_Length ? Util.getInt(rawTlv, i+1, rawTlv[i] & 0x1F) : rawTlv[i];
i = multiByte_Length ? i + (rawTlv[i] & 0x1F) + 1: i + 1;
i += length;
byte[] rawData = new byte[i - start];
Array.Copy(rawTlv, start, rawData, 0, i - start);
BerTlv tlv = new BerTlv(tag, length, i - length, rawData);
result.Add(tlv);
if (constructed_tlv)
parseTlv(tlv.Value, tlv.subTlv);
}
}
}
Here is a utility class that contains some functions used in the class above. It is included for the sake of clarity how it works.
class Util
{
public static string getHexString(byte[] arr)
{
StringBuilder sb = new StringBuilder(arr.Length * 2);
foreach (byte b in arr)
{
sb.AppendFormat("{0:X2}", b);
}
return sb.ToString();
}
public static byte[] getBytes(String str)
{
byte[] result = new byte[str.Length >> 1];
for (int i = 0; i < result.Length; i++)
{
result[i] = (byte)Convert.ToInt32(str.Substring(i * 2, 2), 16);
}
return result;
}
public static int getInt(byte[] data, int offset, int length)
{
int result = 0;
for (int i = 0; i < length; i++)
{
result = (result << 8) | data[offset + i];
}
return result;
}
}

Related

Hashing file larger than 5 gig throws Out of memory exception

I am converting an IBrowserfile to a stream of 6gig. I am trying to hash the file in chunks but getting the Out Of Memory exception,
public static async Task<byte[]> hashmultiblock(Stream stream)
{
int chunckSize = 30000000;
int totalChunks = (int)(stream.Length / chunckSize);
if (stream.Length % chunckSize != 0)
totalChunks++;
using (SHA256 hashAlgorithm = SHA256.Create())
{
int offset = 0;
for (int i = 0; i < totalChunks; i++)
{
long position = (i * (long)chunckSize);
int toRead = (int)Math.Min(stream.Length - position + 1, chunckSize);
byte[] buffer = new byte[toRead];
if (i == totalChunks)
hashAlgorithm.TransformFinalBlock(buffer.ToArray(), 0, toRead);
else
hashAlgorithm.TransformBlock(buffer.ToArray(), 0, toRead, null, -1);
}
return hashAlgorithm.Hash;
}
}

Converts a string into an array of bytes dart

I am consuming a web service that return an XML of data, how can i convert a string containing lexical representation xsd:hexBinary not base64 format to Uint8List, coming from java i can do this by :
import javax.xml.bind.DatatypeConverter;
....
byte[] decoder = DatatypeConverter.parseHexBinary(hexStringXls);
or
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Is this what you want?
final s = "somestring";
final List<int> bytes = s.codeUnits;
https://api.dart.dev/stable/2.8.4/dart-core/String/codeUnits.html

mergsort printing a strange result

I am having an issue with my merge sort, when I print out my sortedArray it only returns [ 0.0, 0.0.....] Im not sure if there is an error in my sort code or in my print line or if it has to do with doubles. The code I am us posted below.
By calling System.out.println(toString(sortedArray) I get an even more obscure answer.
Thanks for any help.
package mergesort;
import java.util.Arrays;
import java.util.Random;
public class mergesort {
public static void main(String[] args) {
double[] array = getIntArray();
long before = System.nanoTime();
double[] sortedArray= mergeSort(array);
System.out.println("Sorting took "+ (System.nanoTime() - before) +" nanoseconds ");
System.out.println(toString(array) + "\n\n" + toString(sortedArray) + "\n main method completed in: " + (System.nanoTime() - before) + " nanoseconds.");
}
private static String toString(double[] array) {
StringBuilder sb = new StringBuilder("[ ");
double len = array.length;
for(int i = 0; i < len - 1; i++) {
sb.append(array[i] + ", ");
}
sb.append(array[(int) (len - 1)] + " ]");
return sb.toString();
}
public static double[] mergeSort(double[] array) {
if (array.length <= 1) {
return array;
}
int half = array.length / 2;
return merge(mergeSort(Arrays.copyOfRange(array, 0, half)),
mergeSort(Arrays.copyOfRange(array, half, array.length)));
}
private static double[] merge(double[] ds, double[] ds2) {
int len1 = ds.length, len2 = ds2.length;
int totalLength = len1 + len2;
double[] result = new double[totalLength];
int counterForLeft =0,counterForRight=0,resultIndex=0;
while(counterForLeft<len1 || counterForRight < len2){
if(counterForLeft<len1 && counterForRight < len2){
if(ds[counterForLeft]<= ds2[counterForRight]){
result[resultIndex++] =(int) ds[counterForLeft++];
} else {
result[resultIndex++] =(int) ds2[counterForRight++];
}
}else if(counterForLeft<len1){
result[resultIndex++] = (int) ds[counterForLeft++];
}else if (counterForRight <len2){
result[resultIndex++] =(int) ds2[counterForRight++];
}
}
return result;
}
private static double[] getIntArray() {
double[] array = new double[10000];
Random random = new Random();
for(int i = 0; i < 10000; i++) {
array[i] = (random.nextDouble() * .99999);
}
return array;
}
}
In the merge method, when copying from one of the input arrays to the results, you cast to int. For example:
result[resultIndex++] =(int) ds[counterForLeft++];
All your doubles are in the range [0...1), so the result of casting any of them to int is zero. Just get rid of those casts, and you will keep your numbers in the merge result.
As an additional tip, it is much easier to debug small problems than large ones. It failed for any size greater than 2, so you should have been debugging with size 2, not 10000.

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

Last block generated differently for AES 128 Encryption (between iOS and .NET)

I have problem converting .NET C# AES 128 Encryption to iOS (iPhone). Everything generated correctly except the last block. The final call to xfrm.TransformFinalBlock generate differently than what I got from iOS code (using CCCryptorFinal). I am using the same parameter for BlockSize, Key and IV. What else am I missing? Thank you.
Obj-C
CCCryptorStatus ccStatus = kCCSuccess;
CCCryptorRef thisEncipher = NULL;
// Create and Initialize the crypto reference.
ccStatus = CCCryptorCreate(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
szKey,
kCCKeySizeAES128,
iv,
&thisEncipher
);
// Calculate byte block alignment for all calls through to and including final.
int bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, InputLength, true);
unsigned char *szResult = (unsigned char *)malloc(bufferPtrSize+1);
memset(szResult, 0x00, bufferPtrSize+1);
while (dataEncrypted < dataToEncrypt)
{
bool final = (dataToEncrypt - dataEncrypted) <= lrcEncryptionBlockSize;
if (final)
{
// Finalize everything to the output buffer.
ccStatus = CCCryptorFinal(thisEncipher,
szResult + dataEncrypted,
bufferPtrSize - dataEncrypted,
pOutSize
);
dataEncrypted += *pOutSize;
for(int c=0;c<dataEncrypted;++c)
{
printf("\n%d => %d\n", c, szResult[c]);
}
success = true;
break;
}
else
{
// Actually perform the encryption or decryption.
ccStatus = CCCryptorUpdate( thisEncipher,
szInput+cb,
lrcEncryptionBlockSize,
szResult+dataEncrypted,
bufferPtrSize - dataEncrypted,
pOutSize
);
dataEncrypted += *pOutSize;
cb += lrcEncryptionBlockSize;
}
}
if (thisEncipher) {
(void) CCCryptorRelease(thisEncipher);
thisEncipher = NULL;
}
C#
AesManaged aesAlg = new AesManaged();
ICryptoTransform xfrm;
aesAlg.IV = GenerateIV();
aesAlg.Key = "1111111111111111";
aesAlg.BlockSize = 128;
xfrm = aesAlg.CreateEncryptor();
while (dataEncrypted < dataToEncrypt)
{
bool final = (dataToEncrypt - dataEncrypted) <= lrcEncryptionBlockSize;
int nbytes = !final ? lrcEncryptionBlockSize : (int)(dataToEncrypt - dataEncrypted);
if (final)
{
byte[] finalblock = xfrm.TransformFinalBlock(message, cb, nbytes);
Buffer.BlockCopy(finalblock, 0, message, cb, lrcEncryptionBlockSize);
success = true;
break;
}
else
{
dataEncrypted += (uint)xfrm.TransformBlock(message, cb, nbytes, message, cb);
cb += lrcEncryptionBlockSize;
}
}
xfrm.Dispose();
aesAlg.Clear();
If only the last block differs, the difference is probably that they use different padding. The first example uses PKCS7, but I cant see what the second one uses.