Turn a human readable string into an image to be displayed with data-uris - ruby

Is there any conventional way to turn an arbitrary string into an image?
In my use case, lets say I want to have an image for each user that maps directly to that user's name.
The concept is similar to QR codes, except the output image is not designed to be readable, simple pretty and consistent.
ultimately i want something like:
def to_image(a_string)
... #magic
return a_data_uri
end
such that
# is always true
to_image("specific string") == to_image("specific string")
Ideally you'd end up with some nice looking fractal-art like image.
If what I'm describing is nonsensical, a function that can convert a string to a data-uri containing a qr code will do.

One possibility would be to hash the strings - this gives you unique numbers as output. Then you can pass these numbers as input param to a fractal generating function.
For hashing either use a real hash function, or (in case the number of users is limited) you can use a CRC function (CRC16, CRC32). Both approaches will give you uniques numbers as output. For CRC you must be a little bit more careful - for instance having 60K input strings and using CRC16 might end up with some clashes (different strings - same CRC16 number).

Related

Algorithm to let a program has a pre-defined hash value?

Let's put it via an intuitive example.
I don't want others to modify my source code, so I put a statement in my code:
if( hash_value_of(this_file) != "A_PRE-DEFINED_HASH_VALUE" )
output("Aha! You modified my file!")
So in this case, the pre-defined hash value will affect the actual hash value of the source file at the output stage. It's like a strange loop so that I have to find a way to calculate a hash value beforehand that exactly matches the output.
It is of note that actually I don't care if this method can protect my source file at all. It is just an example. What of concern is how to calculate such a hash value beforehand.
Is there any algorithm matches the need? I am not expecting to get answers like "why do you even think about it?", "what's the usage?". It's only an algorithm discussion. Thanks for any contribution!

Taking fixnum as user input

I was wondering if there is a way to take user input as a fixnum. I can do something like a = gets.chomp.to_i, but is there anything similar in ruby to nextInt() in java, or do I need to do these conversions each time?
When you're working with input streams, like a file or the terminal, you're working with raw bytes. You never work directly with primitive types. If you want primitive types, you have to use methods to make sense of the bytes. In many cases, "working with raw bytes" is synonymous with working with strings, so strings types often have conversion methods to extract typed data out of them.
Java has the Scanner class, which does have a nextInt() method. It is used to extract a Java integer out of text. It does so by parsing the text and converting it to the requested primitive data type, in this case int. In order for it to work, you must give it an input source. When you wrap it around System.in, you get a Scanner that extracts data from standard input, which is usually connected to the terminal.
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
In Ruby, we can simply ask the string to try and convert itself to another type. If you want an integer:
line = gets # reads from standard input
i = line.to_i # converts the string to an integer
String's to_i method performs a very loose conversion, and returns zero if it couldn't figure out the number or if there was no number to begin with. It will never raise an exception and will always return a number, even if there was no number to parse.
The Integer() method performs a more strict conversion.
First of all, your gets.chomp.to_i works, but is not the right way. I don't know how you got that idea to attach chomp, but that has no meaning here. You should do gets.to_i. So, no, you don't need to do the conversion gets.chomp.to_i each time.
And the only thing Ruby can receive from a terminal input is a string. There is no way to receive anything other than a string from the terminal.

JSON generate unique hash value (SHA-512)

I'm searching for a way to generate a SHA-512 hash from a json string in Ruby, independent from the positions of the elements in it, and independent from nestings, arrays, nested arrays and so on. I just want to hash the raw data along with its keys.
I tried some approaches with converting the JSON into a ruby hash, deep sort them by their keys, append everything into one, long string and hash it. But I bet that my solution isn't the most efficient one, and that there must be a better way to do this.
EDIT
So far, I convert JSON into a Ruby hash. Then I try to use this function to get a canonical representation:
def self.canonical_string_from_hash value, key=nil
str = ""
if value.is_a? Hash
value.keys.sort.each do |k|
str += canonical_string_from_hash(value[k], k)
end
elsif value.is_a? Array
str += key.to_s
value.each do |v|
str += canonical_string_from_hash(v)
end
else
str += key ? "#{key}#{value}" : value.to_s
end
return str
end
But I'm not sure, if this is a good and efficient way to do this.
For example, this hash
hash = {
id: 3,
zoo: "test",
global: [
{ukulele: "ringding", blub: 3},
{blub: nil, ukulele: "rangdang", guitar: "stringstring"}
],
foo: {
ids: [3,4,5],
bar: "asdf"
}
}
gets converted to this string:
barasdfids345globalblub3ukuleleringdingblubguitarstringstringukulelerangdangid3zootest
But I'm not sure, if this is a good and efficient way to do this.
Depends on what you are trying to do. Your canonical/equivalent structures need to represent what is important to you for the comparison. Removing details such as object structure makes sense if you consider two items with different structure but same string values equivalent.
According to your comments, you are attempting to sign a request that is being transferred from one system to a second one. In other words you want security, not a measure of similarity or a digital fingerprint for some other purpose. Therefore equivalent requests are ones that are identical in all the ways that affect the processing that you want to protect. It is simpler, and very likely more secure, to lock down the raw bytes of data that transfer between your two systems.
In which case your whole approach needs a re-think. The reasons for that are probably best discussed on security.stackoverflow.com
However, in brief:
Use an HMAC routine (HMAC-SHA512), it is designed for your purpose. Instead of a salt, this uses a secret, which is essentially the same thing (in fact you need to keep your salt a secret in your implementation too, which is unusual for something called a salt), but has been combined with the SHA in a way which makes it resilient to a couple of attack forms possible against simple concatenation followed by SHA. The worst of these is that it is possible to extend the data and have it generate the same SHA when processed, without needing to know the salt. In other words, an attacker could take a known valid request and use it to forge other requests which will get past your security check. Your proposed solution looks vulnerable to this form of attack to me.
Unpacking the request and analysing the details to get a "canonical" view of the request is not necessary, and also reduces the security of your solution. The only reason for doing this is that you are for some reason not able to handle the request once it has been serialised to JSON, and are forced to work only with the de-serialised request at one end or another of the two systems. If that is purely a knowledge or convenience thing, then fix that problem rather than trying to roll your own security protocol using SHA-512.
You should sign the request, and check the signature, against the fully serialised JSON string. If you need to de-serialise data from a "man-in-the-middle" attack, then you are potentially already exposed to some attacks via the parser. You should work to reject suspect requests before any data processing has been done to them.
TL;DR - ALthough not a direct answer to your question, the correct solution for you is to not write this code at all. Instead you need to place your secure signature code closer to the ins and outs of your two services that need to trust each other.

Turn string into number in Racket

I used read to get a line from a file. The documentation said read returns any, so is it turning the line to a string? I have problems turning the string "1" to the number 1, or "500.8232" into 500.8232. I am also wondering if Racket can directly read numbers in from a file.
Check out their documentation search, it's complete and accurate. Conversion functions usually have the form of foo->bar (which you can assume takes a foo and returns a bar constructed from it).
You sound like you're looking for a function that takes a string and returns a number, and as it happens, string->number does exist, and does pretty much exactly what you're looking for.
Looks like this was answered in another question:
Convert String to Code in Scheme
NB: that converts any s-expression, not just integers. If you want just integers, try:
string->number
Which is mentioned in
Scheme language: merge two numbers
HTH

Calculating Event Horizons in Ruby

this is my first post here. I started using Ruby just 2 days ago and think it is an amazing language, however I have been getting stuck. My problem is I am wanting to calculate the event horizon of a black hole given an input defined in the code as "m" This will then be put into a calculation and the size then printed out to the screen. I did need it to be in binary and thats where I am having the issue.
Here is my code so far.
#Event Horizon Calculation Program
G = 6.67*10**-11
m = 20
C = 200000
R = G*m/(C**2)
puts "Here is the result in Binary."
R.to_i(2)
puts R
Now I do realise that the number are not accurate, that dosen't matter at the moment. I just need the function to work.
Thankyou,
Ross.
Your post is not even in a format of asking a question, but guessing from what you wrote, it seems that you are asking how to change your code so that it accepts an input to m and outputs the result. My answer is based on this assumption.
In order to take an input, use the 'gets' method. So, you may want to replace your 'm = 20' line with:
m = gets.to_f
'gets' accepts an input as a string, so you need to convert it to a numeric. to_f changes a string into a float. You can use to_i instead if you want an integer.
You have a line 'R.to_i(2)', and it seems like you want to output this, but you have two problems here. First of all, whatever that creates, it is only creating something in that position, and does not change the value of R, so, in effect, it actually does nothing. Second, ruby can accept numerals in source code written in different bases such decimal, binary, hex, etc., but it only has one internal representation, and you cannot output a numeral in binary. For your purpose, you need to convert it to a string that corresponds to a binary expression. For that, use the 'to_s' method. In fact, the 'to_i' method does not take an argument. Delete your line 'R.to_i(s)', and replace the line 'puts R' with:
puts R.to_s(2)

Resources