.net To Mono -> System.Security.Cryptography.CryptographicException: Private/public key mismatch - c#

Unhandled Exception: System.Security.Cryptography.CryptographicException: Private/public key mismatch
at Mono.Security.Cryptography.RSAManaged.ImportParameters (RSAParameters parameters) [0x00000] in <filename unknown>:0
at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters (RSAParameters parameters) [0x00000] in <filename unknown>:0
at BlaBlaFunc() [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.Security.Cryptography.CryptographicException: Private/public key mismatch
at Mono.Security.Cryptography.RSAManaged.ImportParameters (RSAParameters parameters) [0x00000] in <filename unknown>:0
at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters (RSAParameters parameters) [0x00000] in <filename unknown>:0
at BlaBlaFunc() [0x00000] in <filename unknown>:0
Here is the Source Code:
string foo = "blabla";
System.Security.Cryptography.RSAParameters rsa_params = new System.Security.Cryptography.RSAParameters();
rsa_params.Modulus = Enumerable.Range(0, pubkey.Length)
.Where(x => x % 2 == 0)
.Select(x => System.Convert.ToByte(pubkey.Substring(x, 2), 16))
.ToArray();
rsa_params.Exponent = new byte[] { 1, 0, 1 };
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
System.Security.Cryptography.RSAParameters d = rsa.ExportParameters(false);
rsa.ImportParameters(rsa_params);
byte[] sp = rsa.Encrypt(Encoding.UTF8.GetBytes(foo), false);
The .exe file which works fine in windows is compiled with vs2010. It was runned with mono under Ubuntu.
Run with this command:
mono --runtime=v4.0.30319 xxx.exe
How can i fix this?

Apparently the ExportParameters call generates a keypair, including private key, even though you specified false for the includePrivateParameters argument. (See the source code). The ImportParameters then overwrites only the public key (because you don't provide the private one) hence the mismatch. This may be a mono bug if it doesn't match documented behaviour. Check that and file a bug if applicable.
As a workaround, you can remove the ExportParameters or create a new instance that you import into.

Related

UCanAccess, IKVM and C#

I'm trying to make UCanAccess work in C#. I'm working on MonoDevelop using Mono on Linux. I already converted the needed .jar files into .dll .NET files using IKVM, this way:
ikvmc -target:library file.jar
Then I referenced the converted .dll files in my C# project. So, here is all DLLs I referenced:
ucanaccess-3.0.3.1.dll
hsqldb.dll
jackcess-2.1.3.dll
commons-logging-1.1.1.dll
commons-lang-2.6.dll
IKVM.OpenJDK.Core.dll
IKVM.OpenJDK.Jdbc.dll
IKVM.Runtime
I also put ucanaccess-3.0.3.1.jar, hsqldb.jar, jackcess-2.1.3.jar, commons-logging-1.1.1.jar and commons-lang-2.6.jar into my bin/Debug folder.
And here is the C# code I wrote in Main:
//ikvm.runtime.Startup.addBootClassPathAssemby(System.Reflection.Assembly.Load("commons-lang-2.6"));
//ikvm.runtime.Startup.addBootClassPathAssemby(System.Reflection.Assembly.Load("commons-logging-1.1.1"));
//ikvm.runtime.Startup.addBootClassPathAssemby(System.Reflection.Assembly.Load("jackcess-2.1.3"));
//ikvm.runtime.Startup.addBootClassPathAssemby(System.Reflection.Assembly.Load("hsqldb"));
ikvm.runtime.Startup.addBootClassPathAssemby(System.Reflection.Assembly.Load("ucanaccess-3.0.3.1"));
java.sql.Driver v_driver = (java.sql.Driver) java.lang.Class.forName("net.ucanaccess.jdbc.UcanaccessDriver, ucanaccess-3.0.3.1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").newInstance();
java.sql.Connection v_con = v_driver.connect("northwind.mdb", null);
//java.lang.Class.forName("org.hsqldb.jdbcDriver, hsqldb, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
//java.lang.Class.forName("net.ucanaccess.jdbc.UcanaccessDriver, ucanaccess-3.0.3.1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
//java.sql.Connection v_con = java.sql.DriverManager.getConnection("jdbc:ucanaccess://northwind.mdb");
java.sql.Statement v_st = v_con.createStatement();
java.sql.ResultSet v_res = v_st.executeQuery("select * from Categories");
java.sql.ResultSetMetaData v_resmd = v_res.getMetaData();
for (int i = 0; i < v_resmd.getColumnCount(); i++)
Console.Write(v_resmd.getColumnLabel(i) + "|");
Console.WriteLine();
while (v_res.next())
{
for (int i = 0; i < v_resmd.getColumnCount(); i++)
Console.Write(v_res.getString(i) + "|");
Console.WriteLine();
}
The code compiles and when I try to execute, here is the error I got:
Unhandled Exception:
System.TypeInitializationException: An exception was thrown by the type initializer for net.ucanaccess.jdbc.UcanaccessDriver ---> java.lang.RuntimeException: org.hsqldb.jdbc.JDBCDriver
--- End of inner exception stack trace ---
at (wrapper managed-to-native) System.Runtime.CompilerServices.RuntimeHelpers:RunClassConstructor (intptr)
at System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor (RuntimeTypeHandle type) [0x00000] in <filename unknown>:0
at IKVM.Internal.TypeWrapper.RunClassInit () [0x00000] in <filename unknown>:0
at IKVM.NativeCode.java.lang.Class.forName0 (System.String name, Boolean initialize, java.lang.ClassLoader loader) [0x00000] in <filename unknown>:0
at java.lang.Class.forName0 (System.String , Boolean , java.lang.ClassLoader ) [0x00000] in <filename unknown>:0
at java.lang.Class.forName (System.String className, ikvm.internal.CallerID ) [0x00000] in <filename unknown>:0
at java.lang.Class.forName (System.String className) [0x00000] in <filename unknown>:0
at Test.MainClass.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: An exception was thrown by the type initializer for net.ucanaccess.jdbc.UcanaccessDriver ---> java.lang.RuntimeException: org.hsqldb.jdbc.JDBCDriver
--- End of inner exception stack trace ---
at (wrapper managed-to-native) System.Runtime.CompilerServices.RuntimeHelpers:RunClassConstructor (intptr)
at System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor (RuntimeTypeHandle type) [0x00000] in <filename unknown>:0
at IKVM.Internal.TypeWrapper.RunClassInit () [0x00000] in <filename unknown>:0
at IKVM.NativeCode.java.lang.Class.forName0 (System.String name, Boolean initialize, java.lang.ClassLoader loader) [0x00000] in <filename unknown>:0
at java.lang.Class.forName0 (System.String , Boolean , java.lang.ClassLoader ) [0x00000] in <filename unknown>:0
at java.lang.Class.forName (System.String className, ikvm.internal.CallerID ) [0x00000] in <filename unknown>:0
at java.lang.Class.forName (System.String className) [0x00000] in <filename unknown>:0
at Test.MainClass.Main (System.String[] args) [0x00000] in <filename unknown>:0
The commented lines I already tried, with no success.
Am I missing something? Thanks in advance!
EDIT:
#jamadei was right, I merged all jars into one single jar and it worked!
Here is the working code (note that column indexes start in 1, not in 0):
ikvm.runtime.Startup.addBootClassPathAssemby(System.Reflection.Assembly.Load("ucanaccess-3.0.3.1"));
java.sql.Driver v_driver = (java.sql.Driver) java.lang.Class.forName("net.ucanaccess.jdbc.UcanaccessDriver, ucanaccess-3.0.3.1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").newInstance();
java.sql.Connection v_con = v_driver.connect("northwind.mdb", null);
java.sql.Statement v_st = v_con.createStatement();
java.sql.ResultSet v_res = v_st.executeQuery("select categoryid, categoryname, description from Categories");
java.sql.ResultSetMetaData v_resmd = v_res.getMetaData();
for (int i = 1; i <= v_resmd.getColumnCount(); i++)
Console.Write(v_resmd.getColumnLabel(i) + "|");
Console.WriteLine();
while (v_res.next())
{
for (int i = 1; i <= v_resmd.getColumnCount(); i++)
Console.Write(v_res.getString(i) + "|");
Console.WriteLine();
}
You need to merge all jars into one single jar and then converting it into dll.

Accessing NetworkManager Connection Settings through dbus-sharp

I'm running Arch Linux with the following version of mcs:
>mcs --version
Mono C# compiler version 4.0.4.0
And the following version of dbus-sharp
>pacman -Ss dbus-sharp
extra/dbus-sharp 0.8.1-1 [installed] C# implementation of D-Bus
extra/dbus-sharp-glib 0.6.0-1 [installed] C# GLib implementation of D-Bus
This is my test program, based on the example code found here: https://gist.github.com/Ummon/4317268
I'm just trying to access the settings of the currently active connection, which should be returned as a 'Dict of {String, Dict of {String, Variant}}' as I've checked in the d-feet tool for the org.freedesktop.NetworkManager.Settings.Connection interface
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using DBus;
namespace NetworkManagerDictTest {
public class MyTest {
[Interface("org.freedesktop.NetworkManager.Settings.Connection")]
public interface IConnection {
IDictionary<string, IDictionary<string, object>> GetSettings();
}
readonly static string BUS_NAME = "org.freedesktop.NetworkManager";
public static void Main(string[] argv) {
org.freedesktop.DBus.Properties NetworkManagerProps = Bus.System.GetObject<org.freedesktop.DBus.Properties>(BUS_NAME, new ObjectPath("/org/freedesktop/NetworkManager"));
ObjectPath[] activeConnections = NetworkManagerProps.Get(BUS_NAME, "ActiveConnections") as ObjectPath[];
if (activeConnections.Length > 0) {
org.freedesktop.DBus.Properties ActiveConnectionProperties = Bus.System.GetObject<org.freedesktop.DBus.Properties>(BUS_NAME, activeConnections[0]);
ObjectPath ActiveConnectionPath = ActiveConnectionProperties.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") as ObjectPath;
Console.WriteLine("Using connection path: " + ActiveConnectionPath);
IConnection connection = Bus.System.GetObject<IConnection>(BUS_NAME, ActiveConnectionPath);
Console.WriteLine("Connection Object ok");
IDictionary<string, IDictionary<string, object>> settings = connection.GetSettings();
Console.WriteLine(settings);
}
}
}
}
Compilation went without errors nor warnings:
mcs Test.cs -r:/usr/lib/mono/dbus-sharp-2.0/dbus-sharp.dll -r:/usr/lib/mono/dbus-sharp-glib-2.0/dbus-sharp-glib.dll
However my program crashes during execution with the following output:
>mono Test.exe
Using connection path: /org/freedesktop/NetworkManager/Settings/0
Connection Object ok
Unhandled Exception:
DBus.Protocol.MessageReader+PaddingException: Read non-zero byte at position 28 while expecting padding. Value given: 200
at DBus.Protocol.MessageReader.ReadPad (Int32 alignment) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadStruct (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadValue (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadDictionary[String,IDictionary`2] () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest+IConnectionProxy.GetSettings () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest.Main (System.String[] argv) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: DBus.Protocol.MessageReader+PaddingException: Read non-zero byte at position 28 while expecting padding. Value given: 200
at DBus.Protocol.MessageReader.ReadPad (Int32 alignment) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadStruct (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadValue (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadDictionary[String,IDictionary`2] () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest+IConnectionProxy.GetSettings () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest.Main (System.String[] argv) [0x00000] in <filename unknown>:0
What can I do to work around this problem? Am I making a mistake when working with the DBus? It seems that all the method calls up to GetSettings went without issues. I've also encountered a similar problem while trying to fix a bug in another project where dbus-sharp would throw an exception when calling GetSettings. Could this be an issue of dbus-sharp instead?
Taking a look at the source code it seems that dbus-sharp infers the return type directly from the signature of the declared method. Unfortunately it doesn't check if I'm using a parent class or interface of Dictionary, eventually it tries to read a DBus struct because of a fallback case which causes the exception as DBus structs are 8 byte padded while dicts use 4 bytes
Replacing all the IDictionary types with Dictionary worked fine and solved my problem.

Xamarin Android: System.IO.Compression.ZipFile.ExtractToDirectory Fails in release mode

Everything works fine in debug mode but when we run it in release the ExtractToDirectory call fails.
Here is the function for reference. Just to make sure we are not doing anything weird.
private bool UnzipFiles()
{
bool toReturn = true;
try
{
UpdateStatus("Almost done...");
string file = Path.Combine (DownloadFolder, "ZipFile.zip");
if(System.IO.Directory.Exists(UnzippingDestinationFolder))
{
System.IO.Directory.Delete(UnzippingDestinationFolder, recursive:true);
}
System.IO.Compression.ZipFile.ExtractToDirectory(file, UnzippingDestinationFolder);
UpdateStatus("Finished!");
var files = System.IO.Directory.GetFiles(UnzippingDestinationFolder);
int m = 3;
}
catch (Exception e)
{
toReturn = false;
}
Finally, here is the exception we get.
System.NullReferenceException: Object reference not set to an instance of an object
at SharpCompress.Common.Zip.Headers.ZipFileEntry.DecodeString (System.Byte[] str) [0x00000] in <filename unknown>:0
at SharpCompress.Common.Zip.Headers.DirectoryEntryHeader.Read (System.IO.BinaryReader reader) [0x00000] in <filename unknown>:0
at SharpCompress.Common.Zip.ZipHeaderFactory.ReadHeader (UInt32 headerBytes, System.IO.BinaryReader reader) [0x00000] in <filename unknown>:0
at SharpCompress.Common.Zip.SeekableZipHeaderFactory+<ReadSeekableHeader>c__Iterator0.MoveNext () [0x00000] in <filename unknown>:0
at SharpCompress.Archive.Zip.ZipArchive+<LoadEntries>c__Iterator0.MoveNext () [0x00000] in <filename unknown>:0
at SharpCompress.LazyReadOnlyCollection`1+LazyLoader[SharpCompress.Archive.Zip.ZipArchiveEntry].MoveNext () [0x00000] in <filename unknown>:0
at System.IO.Compression.ZipArchive.CreateZip (System.IO.Stream stream, ZipArchiveMode mode) [0x00000] in <filename unknown>:0
at System.IO.Compression.ZipArchive..ctor (System.IO.Stream stream, ZipArchiveMode mode, Boolean leaveOpen, System.Text.Encoding entryNameEncoding) [0x00000] in <filename unknown>:0
at System.IO.Compression.ZipFile.Open (System.String archiveFileName, ZipArchiveMode mode, System.Text.Encoding entryNameEncoding) [0x00000] in <filename unknown>:0
at System.IO.Compression.ZipFile.ExtractToDirectory (System.String sourceArchiveFileName, System.String destinationDirectoryName, System.Text.Encoding entryNameEncoding) [0x00000] in <filename unknown>:0
at System.IO.Compression.ZipFile.ExtractToDirectory (System.String sourceArchiveFileName, System.String destinationDirectoryName) [0x00000] in <filename unknown>:0
at NewBaron.Screens.DownloadContentScreen.UnzipFiles () [0x00000] in <filename unknown>:0
A slight changes to Victor's solution. Not linking the SDKs generated an apk that was 53MBs. Too large for the play store's apk size limit.
I set the linking behavior to link SDK assemblies only and it brought the apk size down to 29MBs
Here is the updated window.
#mattewrobbinsdev's suggestion was exactly it. For future readers, here's the dialog in Xamarin Studio:

Does the Unity compiler not fully support named parameters?

The following code compiles just fine in Visual Studio, but in Unity (4.6.x) it creates a compiler error:
public class ErrorTest
{
void DoSomething(bool a = true, bool f = true) { }
void DoSomething(int b, bool f = true) { }
public void SomeMethod()
{
DoSomething(f: false);
}
}
The call to DoSomething is what makes the compiler choke. The question is why, there's really no ambiguity.
The console output when Unity chokes like this:
Internal compiler error. See the console log for more information. output was:
Unhandled Exception: Mono.CSharp.InternalErrorException: Internal error
at Mono.CSharp.MethodGroupExpr.IsApplicable (Mono.CSharp.ResolveContext ec, Mono.CSharp.Arguments& arguments, Int32 arg_count, System.Reflection.MethodBase& method, System.Boolean& params_expanded_form) [0x00000] in <filename unknown>:0
at Mono.CSharp.MethodGroupExpr.OverloadResolve (Mono.CSharp.ResolveContext ec, Mono.CSharp.Arguments& Arguments, Boolean may_fail, Location loc) [0x00000] in <filename unknown>:0
at Mono.CSharp.Invocation.DoResolveOverload (Mono.CSharp.ResolveContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.Invocation.DoResolve (Mono.CSharp.ResolveContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.Expression.Resolve (Mono.CSharp.ResolveContext ec, ResolveFlags flags) [0x00000] in <filename unknown>:0
at Mono.CSharp.Expression.Resolve (Mono.CSharp.ResolveContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.ExpressionStatement.ResolveStatement (Mono.CSharp.BlockContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.StatementExpression.Resolve (Mono.CSharp.BlockContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.Block.Resolve (Mono.CSharp.BlockContext ec) [0x00000] in <filename unknown>:0
at Mono.CSharp.ToplevelBlock.Resolve (Mono.CSharp.FlowBranching parent, Mono.CSharp.BlockContext rc, Mono.CSharp.ParametersCompiled ip, IMethodData md) [0x00000] in <filename unknown>:0
There was/is apparently a bug where combining the use of namespaces and default parameters caused an internal error like this. It was allegedly fixed in 4.5, but from the comments it has been allegedly fixed before. You might try eliminating the namespace declaration in your class as an experiment to see if that bug is what you're experiencing.

c# mono raspberry pi GPIO with Raspberry# getting Operation is not valid

I'm trying to use Raspberry# library to perform basic task whith GPIO pin on Raspberry PI (on and off).
As per example on github: https://github.com/raspberry-sharp/raspberry-sharp-io/wiki/Raspberry.IO.GeneralPurpose
Code:
var led1 = ConnectorPin.P1Pin11.Output();
var connection = new GpioConnection(led1);
for (var i = 0; i < 100; i++)
{
connection.Toggle(led1);
System.Threading.Thread.Sleep(250);
}
connection.Close();
on line var connection = new GpioConnection(led1); I get exception:
"Operation is not valid due to the current state of the object"
Stack trace
Unhandled Exception:
System.InvalidOperationException: Operation is not valid due to the current state of the object
at Raspberry.IO.GeneralPurpose.GpioConnectionDriver..ctor () [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnectionSettings.get_DefaultDriver () [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnectionSettings..ctor () [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnection..ctor (Raspberry.IO.GeneralPurpose.GpioConnectionSettings settings, IEnumerable`1 pins) [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnection..ctor (Raspberry.IO.GeneralPurpose.PinConfiguration[] pins) [0x00000] in <filename unknown>:0
at Hello.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: Operation is not valid due to the current state of the object
at Raspberry.IO.GeneralPurpose.GpioConnectionDriver..ctor () [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnectionSettings.get_DefaultDriver () [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnectionSettings..ctor () [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnection..ctor (Raspberry.IO.GeneralPurpose.GpioConnectionSettings settings, IEnumerable`1 pins) [0x00000] in <filename unknown>:0
at Raspberry.IO.GeneralPurpose.GpioConnection..ctor (Raspberry.IO.GeneralPurpose.PinConfiguration[] pins) [0x00000] in <filename unknown>:0
at Hello.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
I am able to switch pin state with Python so nothing is wrong with device.
Execute your Mono program as root. /dev/mem is not accessible to normal users.
public GpioConnectionDriver() {
using (var memoryFile = UnixFile.Open("/dev/mem", UnixFileMode.ReadWrite | UnixFileMode.Synchronized)) {
gpioAddress = MemoryMap.Create(
IntPtr.Zero,
Interop.BCM2835_BLOCK_SIZE,
MemoryProtection.ReadWrite,
MemoryFlags.Shared,
memoryFile.Descriptor,
Interop.BCM2835_GPIO_BASE
);
}
}
Explanation from here:
http://www.raspberrypi.org/forums/viewtopic.php?f=29&t=22515
To open /dev/mem you need both regular access permissions on the device file and the security capability CAP_SYS_RAWIO, or to be root. There is no getting around this, because full access to memory allows a lot more than just GPIO. It has huge security implications.

Categories

Resources