SCrypt produces different result on x64 platform - scrypt

I am using this library https://github.com/wg/scrypt in my android app.
I can successfully compile it and bind the native implementation in my android app, but the scryptN function produces a different result if it is execute in a 32bit or 64bit environment, how can it be possible?
The java implementation instead works well on both environments
To reproduce the problem, just build the shared libraries with NDK and try to run this function
public String hashPassword(String plainPassword) {
final int shift = 14;
final int n = 1 << shift;
final int r = 8;
final int p = 1;
final int dklen = 64;
try {
return ByteUtils.toHexString(SCrypt.scrypt(
plainPassword.getBytes("utf-8"),
"theseed".getBytes("utf-8"),
n, r, p, dklen));
} catch (Exception e) {
LogHelper.e("error hashing password", e);
return null;
}
}
you will get different outputs if you run on a 32bit architecture or a 64bit one
Thank you

Finally I found a solution:
for anyone using this library on Android, I suggest to use this fork instead
https://github.com/lhunath/scrypt
It has a full android ndk project setup, you just have to run ndk-build from the src/android/jni folder (of course you need to have NDK properly configured) and it will generate a working set of .so files.
NOTE: you have to change the Application.mk file in order to generate them for all platforms

Related

Separate Input And Output In Console In Eclipse

I am using Eclipse to run my java programs but there is a problem with Eclipse's console that the input and output appears in the same console. For example
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t-- > 0) {
int n = scan.nextInt();
System.out.println(n);
}
scan.close();
}
For this code let the input be
2
3
4
then the output that i gets looks like
2
3
43
4
Is there any way to get separate input and output and get the distinction in eclipse.
One could re-assign System.in and/or System.out as discussed here.
Of course, this is not Eclipse-specific solution but a Java one.
I would be working with files in first place.

Call matlab function from Qt using QProcess

I need to call Matlab function from Qt. I know that there are standard way to do it via Engine, but I was not able to connect .lib libraries (I think because I use Mingw compiler). So, as I understand QProcess is the only way to do it. I have studied examples and wrote simple program, which has one QLineEdit(for Matlab script) and two QPushButton (for send script to Matlab and read response). Here is code:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
proc = new QProcess(this);
proc->start("\"C:\\Program Files\\MATLAB\\R2013b\\bin\\matlab.exe\"");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_readButton_clicked()
{
QByteArray dataError = proc->readAllStandardError();
qDebug()<<dataError;
QByteArray dataOutput = proc->readAllStandardOutput();
qDebug()<<dataOutput;
}
void MainWindow::on_writeButton_clicked()
{
QString text = ui->textForMatlab->text();
QByteArray script;
script.append(text);
qDebug()<<script;
proc->write(script);
}
When I start that program matlab.exe is launching. But when I type something in QLineEdit and click write button there is no response from matlab. Could you tell me what I am doing wrong?
try this
QString program = "C:/Program Files/MATLAB/R2013b/bin/matlab";
QStringList arguments;
arguments << "yourarg" << "youragr2";// if u have any aruguments then pass here
QProcess *myProcess = new QProcess(this);
myProcess->start(program, arguments);
if it is not working then try with myProcess->startDetached(program,argumets);

Linking LAPACKE and Eclipse in Ubuntu

I am new to C++ and I am using Eclipse to write a script. My OS is Ubuntu. I need to use the LAPACKE package partially for my code. I however cannot manage to link Eclipse and LAPACKE. I am trying to compile the following sample code:
#include <stdio.h>
#include <lapacke.h>
int main (int argc, const char * argv[])
{
double a[5][3] = {1,1,1,2,3,4,3,5,2,4,2,5,5,4,3};
double b[5][2] = {-10,-3,12,14,14,12,16,16,18,16};
lapack_int info,m,n,lda,ldb,nrhs;
int i,j;
m = 5;
n = 3;
nrhs = 2;
lda = 3;
ldb = 2;
info = LAPACKE_dgels(LAPACK_ROW_MAJOR,'N',m,n,nrhs,*a,lda,*b,ldb);
for(i=0;i<n;i++)
{
for(j=0;j<nrhs;j++)
{
printf("%lf ",b[i][j]);
}
printf("\n");
}
return(info);
}
I am unable to compile the code as my Eclipse throws the error: "Udefined reference to LAPACKE_dgels". I have tried to link Eclipse to LAPACKE, for which I have added the path to LAPACKE header files in the "Paths and Symbols" tab of Eclipse. Can anyone help with what I need to do in order to resolve this issue? I should be missing something ...
I assume you are using gcc compiler. I guess you are missing -llapack flag in the compile arguments. If it doesn't work, try -llapacke. This flag (-l[LibraryName]) tells linker to use external binaries (see: gcc: Difference between -L and -l option AND how to provide complete path to a library).
Check out this question to see how to add compiler flags in Eclipse: How to add compiler options in Eclipse IDE

Problem reading Serial Port C#.net 2.0 to get Weighing machine output

I'm trying to read weight from Sartorius Weighing Scale model No BS2202S using the following code in C#.net 2.0 on a Windows XP machine:
public string readWeight()
{
string lastError = "";
string weightData = "";
SerialPort port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 9600;
port.Parity = Parity.Even;
port.DataBits = 7;
port.StopBits = StopBits.One;
port.Handshake = Handshake.RequestToSend;
try {
port.Open();
weightData = port.ReadExisting();
if(weightData == null || weightData.Length == 0) {
lastError = "Unable to read weight. The data returned form weighing machine is empty or null.";
return lastError;
}
}
catch(TimeoutException) {
lastError = "Operation timed out while reading weight";
return lastError;
}
catch(Exception ex) {
lastError = "The following exception occurred while reading data." + Environment.NewLine + ex.Message;
return lastError;
}
finally {
if(port.IsOpen == true) {
port.Close();
port.Dispose();
}
}
return weightData;
}
I'm able to read the weight using Hyperterminal application (supplied with Windows XP) with the same serial port parameters given above for opening the port. But from the above code snippet, I can open the port and each time it is returning empty data.
I tried opening port using the code given this Stack Overflow thread, still it returns empty data.
Kindly assist me.
I know this is probably old now ... but for future reference ...
Look at the handshaking. There is both hardware handshaking and software handshaking. Your problem could be either - so you need to try both.
For hardware handshaking you can try:
mySerialPort.DtrEnable = True
mySerialPort.RtsEnable = True
Note that
mySerialPort.Handshake = Handshake.RequestToSend
I do not think sets the DTR line which some serial devices might require
Software handshaking is also known as XON/XOFF and can be set with
mySerialPort.Handshake = Handshake.XOnXOff
OR
mySerialPort.Handshake = Handshake.RequestToSendXOnXOff
You may still need to enable DTR
When all else fails - dont forget to check all of these combinations of handshaking.
Since someone else will probably have trouble with this in the future, hand shaking is a selectable option.
In most of the balances you will see the options for Software, Hardware 2 char, Hardware 1 char. The default setting for the Sartorius balances is Hardware 2 Char. I usually recommend changing to Software.
Also if it stops working all together it can often be fixed by defaulting the unit using the 9 1 1 parameter. And then resetting the communication settings.
An example of how to change the settings can be found on the manual on this page:
http://www.dataweigh.com/products/sartorius/cpa-analytical-balances/

How to create chrome crx file programmatically (preferably in java)?

I want to create chrome extension crx file programatically (not using chrome.exe, because it opens new chrome window). So what are the alternatives for same ? My preference is java, but if its possible in other language then also I am okay.
As kylehuff stated, there are external tools that you could use. But you can always use the command line from Google Chrome to do that which is cross platform (Linux / Windows / Mac).
chrome.exe --pack-extension=[extension_path] --pack-extension-key=[extension_key]
--pack-extension is:
Package an extension to a .crx installable file from a given directory.
--pack-extension-key is:
Optional PEM private key is to use in signing packaged .crx.
The above does not run Google Chrome, it is just command line packing using Chromium's core crx algorithm that they use internally.
There is a variety of utilities to do this, in various languages (albeit; they are mostly shell/scripting languages)
I cannot post the links to all of them, because I am a new stackoverflow user - I can only post 1 link, so I created a page which lists them all - including the one C one I speak about below - http://curetheitch.com/projects/buildcrx/6/
Anyway, I spent a few hours and put together a version in C which runs on Windows or Linux, as the other solutions require installation of a scripting language or shell (i.e. python, ruby, bash, etc.) and OpenSSL. The utility I wrote has OpenSSL statically linked so there are no interpreter or library requirements.
The repository is hosted on github, but the link above has a list of my utility and other peoples solutions.
Nothing listed for Java, which was your preference, but hopefully that helps!
//Method to generate .crx. signature
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Signature;
//#param : extenstionContents is your zip file ,
//#returns : byte[] of the signature , use ByteBuffer to merge them and you have your
// .crx
public static byte[] generateCrxHeader(byte[] extensionContents) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
Signature sigInstance = Signature.getInstance("SHA1withRSA");
sigInstance.initSign(pair.getPrivate());
sigInstance.update(extensionContents);
byte [] signature = sigInstance.sign();
byte [] subjectPublicKeyInfo = pair.getPublic().getEncoded();
final int headerLength = 4 + 4 + 4 + 4 + subjectPublicKeyInfo.length + signature.length;
ByteBuffer headerBuf = ByteBuffer.allocate(headerLength);
headerBuf.order(ByteOrder.LITTLE_ENDIAN);
headerBuf.put(new byte[]{0x43,0x72,0x32,0x34}); // Magic number
headerBuf.putInt(2); // Version
headerBuf.putInt(subjectPublicKeyInfo.length); // public key length
headerBuf.putInt(signature.length); // signature length
headerBuf.put(subjectPublicKeyInfo);
headerBuf.put(signature);
final byte [] header = headerBuf.array();
return header;
}
I needed to do this in Ruby. JavaHead's answer looks nice for Java for CRX2. The current format is CRX v3 and header is protobuf based. I wrote a blog for packing an extension with Ruby. There is also a python project from another author.
I'll paste Ruby version of CRX2 and CRX3 methods for packing extensions for a reference here. For complete code see my blog.
So CRX3 method:
def self.header_v3_extension(zipdata, key: nil)
key ||= OpenSSL::PKey::RSA.generate(2048)
digest = OpenSSL::Digest.new('sha256')
signed_data = Crx_file::SignedData.new
signed_data.crx_id = digest.digest(key.public_key.to_der)[0...16]
signed_data = signed_data.encode
signature_data = String.new(encoding: "ASCII-8BIT")
signature_data << "CRX3 SignedData\00"
signature_data << [ signed_data.size ].pack("V")
signature_data << signed_data
signature_data << zipdata
signature = key.sign(digest, signature_data)
proof = Crx_file::AsymmetricKeyProof.new
proof.public_key = key.public_key.to_der
proof.signature = signature
header_struct = Crx_file::CrxFileHeader.new
header_struct.sha256_with_rsa = [proof]
header_struct.signed_header_data = signed_data
header_struct = header_struct.encode
header = String.new(encoding: "ASCII-8BIT")
header << "Cr24"
header << [ 3 ].pack("V") # version
header << [ header_struct.size ].pack("V")
header << header_struct
return header
end
And for historic purposes (this one verified) CRX2:
# #note original crx2 format description https://web.archive.org/web/20180114090616/https://developer.chrome.com/extensions/crx
def self.header_v2_extension(zipdata, key: nil)
key ||= OpenSSL::PKey::RSA.generate(2048)
digest = OpenSSL::Digest.new('sha1')
header = String.new(encoding: "ASCII-8BIT")
signature = key.sign(digest, zipdata)
signature_length = signature.length
pubkey_length = key.public_key.to_der.length
header << "Cr24"
header << [ 2 ].pack("V") # version
header << [ pubkey_length ].pack("V")
header << [ signature_length ].pack("V")
header << key.public_key.to_der
header << signature
return header
end
I have used the excellent service crx-checker to validate both - v2 and v3 extension packing. Where I'm getting the expected RSASSA-PKCS1-v1_5 signature marked (Signature OK) (Developer Signature).
The extension will fail to load with CRX_REQUIRED_PROOF_MISSING if you try to add to your browser from URL because it will be lacking Google signature. But it will be loaded fine by Selenium when running test. To load normally you need to publish on web store.