SHAKE256 inquiry - hash

I am studying at night graduate school.
While studying the cryptographic hash function, I found information that the speed of the SHA3 hash function is faster than the speed of the SHA2 hash function.
So, using JMH benchmarking in actual JAVA, I tried to compare the performance of SHA512/256 of SHA2 and SHAKE256 of SHA3 series, but there doesn't seem to be much difference than I thought.
The library I used and the source code I wrote are as follows.
SHA512-256
import java.security.MessageDigest;
public static byte[] digest(byte[] data) throws NoSuchAlgorithmException
{
CryptoProvider.setupIfNeeded();
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA512/256");
digest.update(Arrays.copyOf(data, data.length));
return digest.digest();
}
SHAKE256 (use 2 methods)
import org.bouncycastle.crypto.digests.SHAKEDigest;
public static byte[] shakeDigest(byte[] data, int returnLength) throws NoSuchAlgorithmException
{
CryptoProvider.setupIfNeeded();
SHAKEDigest digest = new SHAKEDigest(256);
byte[] hashBytes = new byte[returnLength];
digest.update(data, 0, data.length);
digest.doFinal(hashBytes, 0);
digest.reset();
return Arrays.copyOf(hashBytes, returnLength);
}
import com.github.aelstad.keccakj.fips202.Shake256;
public static byte[] shakeDigest2(byte[] data, int returnLength) throws Exception
{
CryptoProvider.setupIfNeeded();
Shake256 digest = new Shake256();
digest.getAbsorbStream().write(data);
byte[] hashBytes = new byte[returnLength];
digest.getSqueezeStream().read(hashBytes);
digest.reset();
return Arrays.copyOf(hashBytes, returnLength);
}
I'm wondering if I'm missing something, or if there exists a SHAKE256 library that's closer to perfection than the one I used.
Please help.
Thank you.

Related

Flutter List<int> LITTLE ENDIAN Order?

I am converting Java code to Dart, but I am stuck in Little Endian oder, Any ideas to help me?
Java:
void displayString(byte[] record) {
ByteBuffer bb = ByteBuffer.wrap(record);
bb.order(ByteOrder.LITTLE_ENDIAN);
.....
}
Dart:
_displayString(List<int> record) {
var _list = Uint8List.fromList(record);
// HOW TO ORDER LITTLE ENDIAN Like Java
.....
}
The closest equivalent to Java Byte buffer is Dart's ByteData.
var byteData = _list.buffer.asByteData();
You can't set its order globally, but you can specify it for each get or set.
byteData.setFloat32(0, 3.04, Endian.little);

Shiros Sha256Hash and alternative algorithms

Is Sha256Hash from Apache Shiro based upon a common specification like PBKDF2WithHmacSHA256?
The following example proves, Shiros Sha256Hash doesn't create a valid PBKDF2WithHmacSHA256 hashes.
public static byte[] getEncryptedPassword(
String password,
byte[] salt,
int iterations,
int derivedKeyLength
) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeySpec keySpec = new PBEKeySpec(
password.toCharArray(),
salt,
iterations,
derivedKeyLength * 8
);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
return f.generateSecret(keySpec).getEncoded();
}
#Test
public void testHashing(){
byte[] salt = new SecureRandomNumberGenerator().nextBytes().getBytes();
byte[] hash1 = new Sha256Hash("1234", salt, 1024).getBytes();
byte[] hash2 = getEncryptedPassword("1234", salt, 1024, 32);
assertTrue(hash1.equals(hash2));
}
Is there a common way to use PBKDF2WithHmacSHA256 with shiro, or do I have to implement my own CredentialMatcher?
Per the Shiro user list on nabble no, Shiro does not provide PBKDF2 (or BCrypt or SCrypt).
Note that Java 8 does have PBKDF2-HMAC-SHA-512 available now as PBKDF2WithHmacSHA512 - use that instead. SHA-512 in particular has 64-bit operations that reduce the advantage GPU based attackers have. Use more iterations than just 1024, as well - see what your system can handle comfortably under load!

iOS: RSA Encrypt using public key (with modulus and exponent)

I'm trying to RSA encrypt an NSData using a public key. The public key is in this format:
<RSAKeyValue>
<Modulus>yOTe0L1/NcbXdZYwliS82MiTE8VD5WD23S4RDsdbJOFzCLbsyb4d+K1M5fC+xDfCkji1zQjPiiiToZ7JSj/2ww==</Modulus>
<Exponent>AWAB</Exponent>
</RSAKeyValue>
After extracting the modulus and exponent from the XML string, how do I get a SecKeyRef out of those to be used as publicKey in the method below?
+ (NSString *)encryptRSA:(NSString *)plainTextString key:(SecKeyRef)publicKey
{
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
uint8_t *cipherBuffer = malloc(cipherBufferSize);
uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
SecKeyEncrypt(publicKey,
kSecPaddingOAEP,
nonce,
strlen( (char*)nonce ),
&cipherBuffer[0],
&cipherBufferSize);
NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
return [encryptedData base64EncodedString];
}
I can't seem to find a definite answer anywhere.
Wow, no wonder it's so hard to find an answer to this. I spent 2 days down the crypto-rabbit hole, and it's not pretty.
The easy way
Use Chilkat iOS RSA Library. One major downside: cost $189! :O
The hard way
Parse the XML, use SCZ-BasicEncodingRules-iOS to generate a public key data out of the modulus and exponent. If that works, create a dummy keychain using that public key (follow sample code here), extract the public key now in SecKeyRef format and pass it to the encryptRSA method in the question. Finally, cleanup, remove the dummy keychain. Sounds good in theory, but I have never tested this thoroughly, if you do, let me know!
I have used the below method for encryption using public key without using any third party libs, guess it may help who is looking for the same after they implemented it just as I did :D
+(NSString *)encryptRSA:(NSString *)plainTextString key:(SecKeyRef)publicKey
{
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
uint8_t *cipherBuffer = malloc(cipherBufferSize);
uint8_t *nonce = (uint8_t *)[plainTextString UTF8String];
SecKeyEncrypt(publicKey,
kSecPaddingPKCS1,
nonce,
strlen( (char*)nonce ),
&cipherBuffer[0],
&cipherBufferSize);
NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
return [encryptedData base64EncodedStringWithOptions:0];
}
I think this will help u!
you can create a java file like fellow:
this java funtion will generate a public key to base64String
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus,16);
BigInteger b2 = new BigInteger(exponent,16);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String encodePublicKey(byte[] encoded) throws Exception{
BASE64Encoder base64Encoder= new BASE64Encoder();
String s=base64Encoder.encode(encoded);
return s;
u should use like :encodePublicKey(publicKey.getEncoded());
Got it!

Blackberry encode MD5 different from MD5 in C#

I have my passwords encoded in MD5 in C# and inserted in my DB.
MD5 MD5Hasher = MD5.Create();
byte[] PasswordHash = MD5Hasher.ComputeHash(Encoding.Unicode.GetBytes(PasswordText.Value));
PasswordHash is inserted as is and look like 0x09C09E5B52580E477514FA.......... for example.
In the blackberry app, I get the password, want to encode it to pass it to a web service that will compare both hashed password. The problem is my result is different from the MD5 I create in my Blackberry app.
password = Crypto.encodeStringMD5(password);
Then below my function:
public static String encodeStringMD5(String s) throws Exception {
byte[] bytes = s.getBytes();
MD5Digest digest = new MD5Digest();
digest.update(bytes, 0, bytes.length);
int length = digest.getDigestLength();
byte[] md5 = new byte[length];
digest.getDigest(md5, 0, true);
return convertToHex(md5);
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
So it returns something like this: 07054da3aea1cc98377fe0..........
Any idea how I can get the same hashed password that I create with my C# function in the Blackberry?
Thank you!
The getBytes() method of java String returns a different encoding than the Encoding.Unicode in .NET. You need to specify unambiguous encoding algorithms. Use UTF-8 for both platforms and you should be ok. You can also try providing a charset name to the getBytes method on the Java side; try getBytes("UTF-16")
GregS answered your question directly; but as an aside I would recommend against having the client create the MD5 sum. If the server manages creating the MD5sum, you can further ensure that the password can't be reverse engineered (eg rainbow table) by adding a "salt" value to the password before encoding it on the server. If you do that on the client, you must expose the salt to the client which is less secure.
Do you check the format? Many languages create the same hashes but in different formats.
For example:
5f45r5ssfds544g56fd4gfd56g4f6dgf
vs.
5f-45-r5-ss-fd-s5-44-g5-6f-d4-gf-d5-6g-4f-6d-gf
Try checking for both formats when converting to a string.

IronRuby performance issue while using Variables

Here is code of very simple expression evaluator using IronRuby
public class BasicRubyExpressionEvaluator
{
ScriptEngine engine;
ScriptScope scope;
public Exception LastException
{
get; set;
}
private static readonly Dictionary<string, ScriptSource> parserCache = new Dictionary<string, ScriptSource>();
public BasicRubyExpressionEvaluator()
{
engine = Ruby.CreateEngine();
scope = engine.CreateScope();
}
public object Evaluate(string expression, DataRow context)
{
ScriptSource source;
parserCache.TryGetValue(expression, out source);
if (source == null)
{
source = engine.CreateScriptSourceFromString(expression, SourceCodeKind.SingleStatement);
parserCache.Add(expression, source);
}
var result = source.Execute(scope);
return result;
}
public void SetVariable(string variableName, object value)
{
scope.SetVariable(variableName, value);
}
}
and here is problem.
var evaluator = new BasicRubyExpressionEvaluator();
evaluator.SetVariable("a", 10);
evaluator.SetVariable("b", 1 );
evaluator.Evaluate("a+b+2", null);
vs
var evaluator = new BasicRubyExpressionEvaluator();
evaluator.Evaluate("10+1+2", null);
First Is 25 times slower than second. Any suggestions? String.Replace is not a solution for me.
I do not think the performance you are seeing is due to variable setting; the first execution of IronRuby in a program is always going to be slower than the second, regardless of what you're doing, since most of the compiler isn't loaded in until code is actually run (for startup performance reasons). Please try that example again, maybe running each version of your code in a loop, and you'll see the performance is roughly equivalent; the variable-version does have some overhead of method-dispatch to get the variables, but that should be negligible if you run it enough.
Also, in your hosting code, how come you are holding onto ScriptScopes in a dictionary? I would hold onto CompiledCode (result of engine.CreateScriptSourceFromString(...).Compile()) instead -- as that will help a lot more in repeat runs.
you can of course first build the string something like
evaluator.Evaluate(string.format("a={0}; b={1}; a + b + 2", 10, 1))
Or you can make it a method
if instead of your script you return a method then you should be able to use it like a regular C# Func object.
var script = #"
def self.addition(a, b)
a + b + 2
end
"
engine.ExecuteScript(script);
var = func = scope.GetVariable<Func<object,object,object>>("addition");
func(10,1)
This is probably not a working snippet but it shows the general idea.