0

I'm currently working on a cryptography system that i build in Java. Before the crypto processing, I need to find the most efficient way to do the following:

After I get a string(f.e. 'plaintext"), i need to split it to its letters and encode them to numbers(f.e. 0-25).

After the cryptographic process i need to do the above on the opposite way, so that the encrypted message(encoded in numbers) is decoded to letters and then letters become one word again.

My main goal is to do what I want in the fastest way i can.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 2
    How about just doing it, before thinking about doing it "the fastest way you can"? Start by deciding what you must do, precisely. Because even if you only accept lowercase letters of the english alphabet, you already need more than 25 distinct numbers. – JB Nizet Dec 24 '16 at 20:17
  • Well, it's my mistake not mentioning that i only accept lowercase or uppercase(choose what you want) and every other character is not accepted. That's why i say 0-25. And i've done it using mapping of each letter, .split method etc. but i need the most efficient way to do it. – Galinho Salonica Dec 24 '16 at 20:23

1 Answers1

0

Although you can use streams:

str.chars().map(c -> c - 'a') // IntStream of 0-25

Due to stream overheads, a plain loop over the bytes will be fastest:

byte[] bytes = str.getBytes(); // OK, since all chars are in range 0-127
for (int i = 0; i < bytes.length; i++)
    bytes[i] = bytes[i] - 'a';

And the reverse to decrypt/construct:

for (int i = 0; i < bytes.length; i++)
    bytes[i] = bytes[i] + 'a';
String plain = new String(bytes);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • getBytes() and new String(bytes) should specify the ASCII charset, instead of relying on the platform default charset. But why even encoding the string to bytes using a charset, rather than just iterating though the chars of the string? – JB Nizet Dec 24 '16 at 20:28
  • Do you mean just number them like a->0, b->1,....z-25 ? That's what i really want to do and that is the best way to move to modulo maths for cryptography in the processes following. – Galinho Salonica Dec 24 '16 at 20:38