If i add this line to my code then it refuses to compile!(This happens with All scripts in unity, even empty ones)
string publicKey = Nethereum.Signer.EthECKey.GetPublicAddress(privatekey);
Code:
using System.Collections;
using System;
using System.Collections.Generic;
using Nethereum.Util;
using UnityEngine;
using System.Threading.Tasks;
using Nethereum.Hex.HexConvertors.Extensions;
using Org.BouncyCastle.Crypto.Digests;
using System.Linq;
using System.Text;
using Nethereum.Util.Keccak;
using System.Numerics;
using System.Runtime.CompilerServices;
using Nethereum.RLP;
using Nethereum.Signer.Crypto;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
public class MianScript : MonoBehaviour
{
string chain = "ethereum";
string network = "rinkeby";
[SerializeField]
public string password;
public void OnClickBTN()
{
string privatekey = CreateAccount();
string publicKey = Nethereum.Signer.EthECKey.GetPublicAddress(privatekey);
Debug.Log("\nPrivate: " + privatekey + "\nPublicKey: " + publicKey);
}
public byte[] CalculateHash(byte[] value)
{
var digest = new KeccakDigest(256);
var output = new byte[digest.GetDigestSize()];
digest.BlockUpdate(value, 0, value.Length);
digest.DoFinal(output, 0);
return output;
}
public async Task<String> GetBalance(string chain1, string network1, string address1)
{
string balance = await EVM.BalanceOf(chain1, network1, address1);
return balance;
}
public static string CreateAccount()
{
System.Random random = new System.Random();
var bytes = new Byte[32];
random.NextBytes(bytes);
var hexArray = Array.ConvertAll(bytes, x => x.ToString("X2"));
var hexStr = String.Concat(hexArray);
return Convert.ToString(hexStr.ToLower());
}
}
Help pls!
I'm not using unity, C# either but it seems that GetPublicAddress() is not a static function but a class method.
So I think you need to do something like that:
// Creating an EthECKey instance
var key = new Nethereum.Signer.EthECKey(privateKey.HexToByteArray(), true);
// Getting the public Address
string publicKey = key.GetPublicAddress();
I simply checked examples from here.
Related
I am attempting to use c# and the Azure.Storage.Blobs.Specialized.BlockBlobClient to upload large files. I am encountering time-outs. I need a sample that shows how to upload large files (approx 300MB). I have not been able to find a good example.
using Azure.Storage.Blobs.Specialized;
...
using (var fs = fileInfo.Open(FileMode.Open,FileAccess.Read))
{
var blockBlobClient = new BlockBlobClient(
connectionString,
"ore",
fileInfo.Name);
await blockBlobClient.UploadAsync(fs);
}
I had to adjust the network timeout.
var uploadManager = new UploadManager();
await uploadManager.UploadBlob(connectionString, container, fileInfo);
This class handles large uploads, increases the network timeout and provides a Progress output.
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uploader
{
public class UploadManager
{
System.Collections.Concurrent.ConcurrentBag<long> progressBag = null;
Progress<long> progressHandler = null;
public UploadManager()
{
progressBag = new System.Collections.Concurrent.ConcurrentBag<long>();
progressHandler = new Progress<long>(progress => progressBag.Add(progress));
progressHandler.ProgressChanged += ProgressHandler_ProgressChanged;
}
public async Task UploadBlob(string connectionString, string container, FileInfo fileInfo)
{
using (var fs = fileInfo.Open(FileMode.Open, FileAccess.Read))
{
var clientOptions = new BlobClientOptions();
clientOptions.Retry.NetworkTimeout = new TimeSpan(0, 0, 600);
var blockBlobClient = new BlockBlobClient(connectionString, container, fileInfo.Name, clientOptions);
var uploadOptions = new BlobUploadOptions();
uploadOptions.ProgressHandler = progressHandler;
await blockBlobClient.UploadAsync(fs, uploadOptions);
}
}
private static void ProgressHandler_ProgressChanged(object sender, long e)
{
Debug.WriteLine($"Progress:{(e / 1000).ToString()} MB");
}
}
}
I'm trying to modify a print ticket since many days. :(
Here is the code :
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Drawing.Printing;
using System.Drawing;
using System.Xml;
// ....
// Get the ticket
var printQueue = new PrintServer("\\\\NetworkNameHere").GetPrintQueue("PrinterNameHere");
PrintTicket userPrintTicket = printQueue.UserPrintTicket;
// Modify the ticket to print in landscape (or any other option)
var xmlDoc = new XmlDocument();
xmlDoc.Load(userPrintTicket.GetXmlStream());
var manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI);
string xpath = string.Format("//psf:Feature[#name='{0}']/psf:Option", "psk:PageOrientation");
XmlNode node = xmlDoc.SelectSingleNode(xpath, manager);
node.Attributes["name"].Value = "psk:Landscape";
PrintTicket modifiedPrintTicket = null;
using (var stream = new MemoryStream())
{
xmlDoc.Save(stream);
stream.Position = 0;
modifiedPrintTicket = new PrintTicket(stream);
}
System.Printing.ValidationResult result = printQueue.MergeAndValidatePrintTicket(printQueue.UserPrintTicket, modifiedPrintTicket);
printQueue.UserPrintTicket = result.ValidatedPrintTicket;
MessageBox.Show(result.ValidatedPrintTicket.PageOrientation.Value.ToString());
printQueue.Commit();
Byte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream.");
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(myByteBuffer, 0, myByteBuffer.Length);
stream.Close();
}
The problem :
Look like the ticket is correctly modified, but for some reasons it never use the information specified in the ticket for any option. HELP!!!!
Note that I'm using .Net 4.0 but I get the same result with the new PrintTicket parameter in addJob (4.5) : printQueue.AddJob("xx", result.ValidatedPrintTicket)
Thanks!
I have connection string encryption/decryption code in c#.net. But when i decrypt the encrypted string just first 8 character decrypting wrong the others are true. What can be the problem ?
I used that codes without Initialization Vector.
https://msdn.microsoft.com/en-us/library/ff649224.aspx
İts the DecryptTransformer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace Encryption
{
internal class DecryptTransformer
{
private EncryptionAlgorithm algorithmID;
private byte[] initVec;
internal DecryptTransformer(EncryptionAlgorithm deCryptId)
{
algorithmID = deCryptId;
}
internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey/*,
byte[] initVec*/)
{
// Pick the provider.
switch (algorithmID)
{
case EncryptionAlgorithm.Des:
{
DES des = new DESCryptoServiceProvider();
des.Mode = CipherMode.CBC;
des.Key = bytesKey;
// des.IV = initVec;
return des.CreateDecryptor();
}
case EncryptionAlgorithm.TripleDes:
{
TripleDES des3 = new TripleDESCryptoServiceProvider();
des3.Mode = CipherMode.CBC;
return des3.CreateDecryptor(bytesKey, initVec);
}
case EncryptionAlgorithm.Rc2:
{
RC2 rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;
return rc2.CreateDecryptor(bytesKey, initVec);
}
case EncryptionAlgorithm.Rijndael:
{
Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
return rijndael.CreateDecryptor(bytesKey, initVec);
}
default:
{
throw new CryptographicException("Algorithm ID '" +
algorithmID +
"' not supported.");
}
}
} //end GetCryptoServiceProvider
internal byte[] IV
{
set { initVec = value; }
}
}
}
its Decryptor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
namespace Encryption
{
public class Decryptor
{
private DecryptTransformer transformer;
private byte[] initVec;
public Decryptor(EncryptionAlgorithm algId)
{
transformer = new DecryptTransformer(algId);
}
public byte[] Decrypt(byte[] bytesData, byte[] bytesKey/*,
byte[] initVec*/)
{
//Set up the memory stream for the decrypted data.
MemoryStream memStreamDecryptedData = new MemoryStream();
//Pass in the initialization vector.
//transformer.IV = initVec;
ICryptoTransform transform =
transformer.GetCryptoServiceProvider(bytesKey/*,initVec*/);
CryptoStream decStream = new CryptoStream(memStreamDecryptedData,
transform,
CryptoStreamMode.Write);
try
{
decStream.Write(bytesData, 0, bytesData.Length);
}
catch(Exception ex)
{
throw new Exception("Error while writing encrypted data to the stream: \n"
+ ex.Message);
}
decStream.FlushFinalBlock();
decStream.Close();
// Send the data back.
return memStreamDecryptedData.ToArray();
} //end Decrypt
public byte[] IV
{
set { initVec = value; }
}
}
}
and Form part
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Encryption;
using System.Text;
using Microsoft.Win32;
namespace datareg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
// Create the encryptor object, specifying 3DES as the
// encryption algorithm
Encryptor enc = new Encryptor(EncryptionAlgorithm.TripleDes);
// Get the connection string as a byte array
byte[] plainText =
Encoding.ASCII.GetBytes(txtConnectionString.Text);
byte[] key = Encoding.ASCII.GetBytes(txtKey.Text);
// Perform the encryption
byte[] cipherText = enc.Encrypt(plainText, key/*,enc.IV*/);
// Store the intialization vector, as this will be required
// for decryption
// txtInitializationVector.Text = Encoding.ASCII.GetString(enc.IV);
// Display the encrypted string
txtEncryptedString.Text = Convert.ToBase64String(cipherText);
}
catch (Exception ex)
{
MessageBox.Show("Exception encrypting: " + ex.Message,
"Encryption ");
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
// Set up the Decryptor object
Decryptor dec = new Decryptor(EncryptionAlgorithm.TripleDes);
// Set the Initialization Vector
dec.IV = Encoding.ASCII.GetBytes(txtInitializationVector.Text);
byte[] key = Encoding.ASCII.GetBytes(txtKey.Text);
// Perform the decryption
byte[] plainText = dec.Decrypt(Convert.FromBase64String(
txtEncryptedString.Text),
key/*,dec.IV*/);
// Display the decrypted string.
txtDecryptedString.Text = Encoding.ASCII.GetString(plainText);
}
catch (Exception ex)
{
MessageBox.Show("Exception decrypting. " + ex.Message,
"Encryption Test Harness");
}
}
private void button4_Click(object sender, EventArgs e)
{
// Create registry key and named values
RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software",true);
rk = rk.CreateSubKey("TestApplication");
// Write encrypted string, initialization vector and key to the registry
rk.SetValue("connectionString",txtEncryptedString.Text);
//rk.SetValue("initVector",
// Encoding.ASCII.GetBytes(txtInitializationVector.Text));
rk.SetValue("key", Encoding.ASCII.GetBytes(txtKey.Text));
MessageBox.Show("The data has been successfully written to the registry");
}
}
}
its the ss
I don't understand this error I am getting. I have tried to clean and build my project several times. Can anyone help me?
Program.cs
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
class Program
{
static void Main(string[] args)
{
var lstWebSites = new List<string>
{
"www.mearstransportation.com",
"www.amazon.com",
"www.ebay.com",
"www.att.com",
"www.verizon.com",
"www.sprint.com",
"www.centurylink.com",
"www.yahoo.com"
};
string filename = #"RequestLog.txt";
{
using (var writer = new StreamWriter(filename, true))
{
foreach (string website in lstWebSites)
{
for (var i = 0; i < 4; i++)
{
MyWebRequest request = new MyWebRequest();
request.Request(website);
}
}
}
}
}
}
}
MyWebRequest.cs - the problem is here: public class MyWebRequest
Error is: "The namespace HttpRequestApp already contains a definition for MyWebRequest"
using HTTPrequestApp.MyWebRequest;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
public class MyWebRequest : IWebRequest
{
public void Request(string strWebSite)
{
List<string> lstWebSites = Program.GetList(strWebSite);
using (var client2 = new TcpClient(strWebSite, 80))
{
using (NetworkStream stream = client2.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader2 = new StreamReader(stream))
{
//writer.AutoFlush = true;
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("HOST: {0}:80", lstWebSites[1]);
writer.WriteLine("Connection: Close");
writer.WriteLine();
writer.WriteLine();
string theresponse = reader2.ReadToEnd();
Console.WriteLine(theresponse);
}
}
}
}
}
IWebRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.IO;
using System.Threading.Tasks;
//using MyWebRequest.Lib;
namespace HTTPrequestApp.MyWebRequest
{
public interface IWebRequest
{
Task<List<strWebSite>> GetList();
void Request();
}
}
To give an over view of what I am trying to accomplish here is: Send HTTP request to get the initial page. Get back the HTTP response and check that it is a 200 response code. And time how long it took to retrieve the response.
This is a console app but I need to not have it depend on the console, it needs to be an independent application so I can use it somewhere else.
If anyone has any suggestions on how I can simplify my code please let me know.
thanks.
You have a HTTPrequestApp.MyWebRequest namespace and a HTTPrequestApp.MyWebRequest class name: c# compiler get confused (and human too...)
Consider renaming the namespace in something such HTTPrequestApp.MyWebRequestNameSpace if you really want a different namespace.
I am trying to create a console or form where you would drag a file onto their respective .exe
The program would get that file and hash it, then set the clipboard text to the proviously generated hash.
This is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string path = args[0];
StreamReader wer = new StreamReader(path.ToString());
wer.ReadToEnd();
string qwe = wer.ToString();
string ert = Hash(qwe);
string password = "~" + ert + "~";
Clipboard.SetText(password);
}
static public string Hash(string input)
{
MD5 md5 = MD5.Create();
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
}
When I get the single .exe from the release, and drag a file onto it, I get some sort of threading error- I can't provide it because it is in the console, not in vb2010. Thanks for any help
Clipboard API uses OLE internally and thus can only be called on a STA thread. Unlike WinForms applications, console applications aren't using STA by default.
Add the [STAThread] attribute to Main:
[STAThread]
static void Main(string[] args)
{
...
Just do what the exception message told you to:
Unhandled Exception: System.Threading.ThreadStateException: Current thread must
be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.
Cleaning up your program a bit:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Windows.Forms;
namespace HashToClipboard
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string hexHash = Hash(args[0]);
string password = "~" + hexHash + "~";
Clipboard.SetText(password);
}
static public string Hash(string path)
{
using (var stream = File.OpenRead(path))
using (var hasher = MD5.Create())
{
byte[] hash = hasher.ComputeHash(stream);
string hexHash = BitConverter.ToString(hash).Replace("-", "");
return hexHash;
}
}
}
}
This has several advantages over your program:
It doesn't need to load the whole file into RAM at the same time
It returns the correct result if the file contains non-ASCII characters/bytes
It'd shorter and cleaner