Cryptographic hashing in Ceylon

£可爱£侵袭症+ 提交于 2019-12-11 08:02:02

问题


What is the recommended way to import the standard cryptographic hashing (message digest) libraries (MD5, SHA1, SHA2, SHA256, SHA3, etc.) in Ceylon?


回答1:


There doesn't seem to be a cryptography module in the SDK.

There is Ceylon Crypto on Github (and as 3 separate modules in Herd), but it says in the README:

Note that IANAC (I am not a cryptologist), so this will surely be flawed in some security relevant way.

Do not use in production and don't rely on it in any expensive way whatsoever!

If you just want to use this in the JVM, I would suggest to use just Java's crypto APIs in java.security (that should be enough for the hash functions) or javax.crypto (for other stuff like ciphers).

Here is an example, calculating the SHA-256 of Hello World:

module.ceylon:

native("jvm")
module example "1.0.0" {
    import java.base "8";
}

run.ceylon:

import java.security {
    MessageDigest
}
import java.lang {
    JString=String,
    ByteArray
}

"Formats a single byte as a (two character) hexadecimal string."
String formatByte(Byte byte)
        => Integer.format(byte.unsigned, 16).padLeading(2, '0');

"Formats a Java byte array as a hexadecimal string."
String formatByteArray(ByteArray result)
        => String.sum(result.byteArray.map(formatByte));

"Calculates SHA-256('Hello World') and print it."
shared void run() {
    value message = "Hello World";
    value bytes = JString(message).getBytes("UTF-8");

    value dig = MessageDigest.getInstance("SHA-256");
    value result = dig.digest(bytes);

    value formatted = formatByteArray(result);
    print("Result: ``result.array```");
    print("Length: ``result.size``");
    print("Result in hex: ``formatted``");
}

This program outputs this:

Result: { -91, -111, -90, -44, 11, -12, 32, 64, 74, 1, 23, 51, -49, -73, -79, -112, -42, 44, 101, -65, 11, -51, -93, 43, 87, -78, 119, -39, -83, -97, 20, 110 }`
Length: 32
Result in hex: A591A6D40BF420404A011733CFB7B190D62C65BF0BCDA32B57B277D9AD9F146E

I didn't find a Ceylon wrapper for this which would make it a bit nicer, though.



来源:https://stackoverflow.com/questions/49717005/cryptographic-hashing-in-ceylon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!