In short, I have a integer value about 10 digits long. I would like to encrypt it using rc4 algorithm in Java. I went online and search, but I could only find encryption for string values/plaintext. Please advise. Thanks!
Asked
Active
Viewed 350 times
2 Answers
1
Can't you just convert the integer to a String
and then encrypt the string?
String myIntegerString = Integer.toString(myInteger)
;- encrypt
myIntegerString
; - store the encrypted
myIntegerString
; - read the encrypted
myIntegerString
; - decrypt
myIntegerString
; Integer.parseInt(myIntegerString)
.

Maarten Bodewes
- 90,524
- 13
- 150
- 263

John Brandli
- 110
- 4
-
1Please try to format your answers to the best of your abilities. This one was so badly formatted and used invalid Java code that I was tempted to downvote instead of adjust. The answer would be greatly improved if you'd show encoding / decoding of the string as well. – Maarten Bodewes Apr 16 '19 at 09:46
1
I assume that you are using the JavaSE API, in particular the javax.crypto.Cipher
class. The encryption API is concerned with generic data, not interpreted in some way; this is why Cipher#doFinal()
takes a byte array. (You may interpret that as a string, given the common terms "plaintext"/"ciphertext".)
The solution to your problem is to convert the integer to a byte array. If "integer" in your case means int
(32-bit), then you need 4 bytes (8-bit). See this question for (multiple good) solutions to this.

pxcv7r
- 478
- 5
- 14
-
Note that the max of `int` in Java is `2,147,483,647`. That's indeed 10 digits, but higher values than the given maximum will fail, i.e. a `long` (or larger things like `BigInteger`) may be required. Of course, you could still easily store that in 5 rather than 8 bytes where required. – Maarten Bodewes Apr 16 '19 at 09:50