converting java to perl (md5) - md5

I am trying converting java to perl (md5)program.
How can i do following two programs same output MD5 sum.
Java
import java.security.MessageDigest;
import java.math.BigInteger;
public class Hash
{
public static void main( String[] args ) throws Exception
{
MessageDigest md5 = MessageDigest.getInstance("MD5");
String plain = "abcd1234";
BigInteger digest = new BigInteger(md5.digest(plain.getBytes("UTF-8")));
System.out.println( digest.abs() );
}
}
Perl
use Digest::MD5 'md5_hex';
use Math::BigInt;
my $plain = "abcd1234";
my $digest = Math::BigInt::->from_hex(md5_hex $plain);
print $digest, "\n";
I Think,
Java:
BigInteger digest = new BigInteger(md5.digest(plain.getBytes("UTF-8")));
Perl:
my $digest = Math::BigInt::->from_hex(md5_hex $plain);
here is diffrent output MD5 sum.
I want to edit perl source.

Your BigInteger() call requires a byte array containing the two's complement binary representation of the number. You need to use the sign-magnitude constructor:
public BigInteger(int signum, byte[] magnitude)
So, your Java code should be:
import java.security.MessageDigest;
import java.math.BigInteger;
public class Hash
{
public static void main(String[] args) throws Exception
{
MessageDigest md5 = MessageDigest.getInstance("MD5");
String plain = "abcd1234";
BigInteger digest = new BigInteger(1, md5.digest(plain.getBytes("UTF-8")));
System.out.println(digest.abs());
}
}
Your Perl code didn't quite work for me, either. My version of Math::BigInt requires a string representation of the hex value, like so:
use Digest::MD5 'md5_hex';
use Math::BigInt;
my $plain = "abcd1234";
my $digest = Math::BigInt::->from_hex('0x' . md5_hex($plain));
print $digest, "\n";
When I run those two commands, I get the same digest value displayed.

Related

DigestUtils.md5Hex() generates wrong hash value when passing String object

I'm trying to generate a md5 hash in Kotlin using the DigestUtils class from the org.apache.commons.codec. Here's the test code
#Test
fun md5Test(){
val userPassword: String = "123"
val md5Hash: String = "202cb962ac59075b964b07152d234b70"
assertEquals(md5Hash, DigestUtils.md5Hex(userPassword))
}
The problem is that when I run this test it fails and says that the generated md5 hash is 28c1a138574866e9c2e5a19dca9234ce
But... when I pass the String value instead of the object
assertEquals(md5Hash, DigestUtils.md5Hex("123"))
The test passes without errors
Why this is happening?
Here is a complete solution to get MD5 base64 hash:
fun getMd5Base64(encTarget: ByteArray): String? {
val mdEnc: MessageDigest?
try {
mdEnc = MessageDigest.getInstance("MD5")
// Encryption algorithmy
val md5Base16 = BigInteger(1, mdEnc.digest(encTarget)) // calculate md5 hash
return Base64.encodeToString(md5Base16.toByteArray(), 16).trim() // convert from base16 to base64 and remove the new line character
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
return null
}
}
This is the most simple and complete solution in kotlin:
val hashedStr = String.format("%032x", BigInteger(1, MessageDigest.getInstance("MD5").digest("your string value".toByteArray(Charsets.UTF_8))))

ChannelHandler handling content of unknown size

I am still struggling with Camel (2.16.1) and Netty (4.0.33) to have them both receive tcp content of freely chosen length. Because of the unknown size of the tcp content received I was not yet able to create a working decoder for.
Let me describe my problem with an example. Lets say I have a file with a length of 3129 byte. When I nc that file to my route the size is not known until the last byte is read:
cat file.bin | nc localhost 10001
My route is defined like this:
from( "netty4:tcp://127.0.0.1:10001?sync=false&allowDefaultCodec=false&
decoder=#factory&receiveBufferSize=1000000")
.to("file:/temp/in");
The factory looks like this because I need to make sure that each ChannelHandler is used only once:
public class Factory implements ChannelHandlerFactory {
#Override
public ChannelHandler newChannelHandler() {
return new RawPrinterDecoder();
}
}
In my decoder I have this code:
public class RawPrinterDecoder extends ReplayingDecoder<Void> {
#Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
List<Object> out) throws Exception {
while (in.isReadable()) {
byte readByte = in.readByte();
job.addContent(readByte);
}
in.discardReadBytes();
}
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Bytes in job: " + job.getSize() );
}
}
The problem with this is that instead of 3129 byte I receive 9273. The reason for this is that the file is split into 3 segments of 1024 byte and 1 with 57 byte. Those are passed repeatedly to my decoder and although I try to invalidate the segments after they are first processed with in.discardReadBytes() they are processed again so instead of ...
segment1
segment2
segment3
segment4
... my decoder sees them like this
segment1
segment1+segment2
segment1+segment2+segment3
segment1+segment2+segment3+segment4
I tried so solve my problem by using checkpoint() but the segments were still called repeatedly.
How can I make sure that each segment is only processed once and in the correct order ? If this can be done more efficiently instead of reading single bytes recommendations are welcome (readableBytes() always return 2 GB so I can not use this to get the number of bytes).
It gets seperated into segments because of the ByteBuffAllocator that your server is using. You can change that this way:
#Bean
public ChannelInitializer<SocketChannel> channelInitializer() {
return new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(2048));
}
};
}
You can read all of the available bytes at once using:
ByteBuf buffer = in.readBytes(in);
or
ByteBuf buffer = in.readSlice(in.readableBytes());

PHP constants - const vs define vs static

Problems:
const variables cannot be concated (but we can achieve this with constant define).
define slows on runtime - especially when you have a long list of defines.
Static - the solution?
define,
define('prefix','hello');
define('suffix','world');
define('greeting',prefix.' '.suffix);
static,
class greeting
{
static public $prefix = 'hello';
static public $suffix = 'world';
static public $concat = 'default';
public function __construct()
{
self::$concat = self::$prefix.' '.self::$suffix;
}
}
Questions:
So which one is faster then? How can I test them?
Why do I have to make an instance of greeting before I can change the default value of $concat (see below)?
greeting Usage:
var_dump(greeting::$concat); // default
new greeting(); // I don't even need to store it in a variable like $object = new greeting();
var_dump(greeting::$concat); // hello world
That is strange. How can I not to make an instance of greeting but still can get the correct result?
Any ideas what I can do to make this better?
static properties are still mutable! What you want are class constants:
<?php
class greeting
{
const prefix = 'hello';
const suffix = 'world';
}
echo greeting::prefix, ' ', greeting::suffix ;
# Yields: Hello world
If you have a lot of constants, you might want to use serialize() to write a cache file and in your code unserialize(). Depending on your use case, the file open + unserialize() might be faster than the PHP runner.

Generating Chrome Packaged App .crx header with Java

I"m trying to build the header in Java with no luck.
(here is the spec: https://developer.chrome.com/extensions/crx)
Any ideas?
protected void geneateCrxHeader (OutputStream ins,byte[] zipArchive) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, InvalidKeyException, SignatureException{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
byte[] key = pair.getPublic().getEncoded();
Signature instance = Signature.getInstance("SHA1withRSA");
instance.initSign(pair.getPrivate());
instance.update(zipArchive);
byte[] hash = instance.sign();
byte[] magic = {0x43,0x72,0x32,0x34,0x02,0x00,0x00,0x00,0x00,0x01,0x0E,0x0B,0x00,0x00,0x08,0x00};
ins.write(magic);
ins.write(key);
ins.write(hash);
}
and I get CRX_EXCESSIVELY_LARGE_KEY_OR_SIGNATURE..
I must be using wrong keygen.
in the docs they do say :
"..the contents of the author's RSA public key, formatted as an X509 SubjectPublicKeyInfo block. .."
i wonder if that is what i'm not doing correctly...
p.s Java crypto is a new frontier for me , so pls don't laugh if I did something totally dumb.
Here is some code that I whipped up and didn't test that illustrates producing just the header. I based this solely on reading the spec.
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Signature;
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;
}

Pointers, functions and arrays in D Programming Language

I'm writing a method to output to several output streams at once, the way I got it set up right now is that I have a LogController, LogFile and LogConsole, the latter two are implementations of the Log interface.
What I'm trying to do right now adding a method to the LogController that attaches any implementation of the Log interface.
How I want to do this is as follows: in the LogController I have an associative array, in which I store pointers to Log objects. When the writeOut method of the LogController is called, I want it to then run over the elements of the array and call their writeOut methods too. The latter I can do, but the previous is proving to be difficult.
Mage/Utility/LogController.d
module Mage.Utility.LogController;
import std.stdio;
interface Log {
public void writeOut(string s);
}
class LogController {
private Log*[string] m_Logs;
public this() {
}
public void attach(string name, ref Log l) {
foreach (string key; m_Logs.keys) {
if (name is key) return;
}
m_Logs[name] = &l;
}
public void writeOut(string s) {
foreach (Log* log; m_Logs) {
log.writeOut(s);
}
}
}
Mage/Utility/LogFile.d
module Mage.Utility.LogFile;
import std.stdio;
import std.datetime;
import Mage.Utility.LogController;
class LogFile : Log {
private File fp;
private string path;
public this(string path) {
this.fp = File(path, "a+");
this.path = path;
}
public void writeOut(string s) {
this.fp.writefln("[%s] %s", this.timestamp(), s);
}
private string timestamp() {
return Clock.currTime().toISOExtString();
}
}
I've already tried multiple things with the attach functions, and none of them. The build fails with the following error:
Mage\Root.d(0,0): Error: function Mage.Utility.LogController.LogController.attach (string name, ref Log l) is not callable using argument types (string, LogFile)
This is the incriminating function:
public void initialise(string logfile = DEFAULT_LOG_FILENAME) {
m_Log = new LogController();
LogFile lf = new LogFile(logfile);
m_Log.attach("Log File", lf);
}
Can anyone tell me where I'm going wrong here? I'm stumped and I haven't been able to find the answer anywhere. I've tried a multitude of different solutions and none of them work.
Classes and interfaces in D are reference types, so Log* is redundant - remove the *. Similarly, there is no need to use ref in ref Log l - that's like taking a pointer by reference in C++.
This is the cause of the error message you posted - variables passed by reference must match in type exactly. Removing the ref should solve the error.

Resources