1

I have a requirement of of encrypt and decrypt the text but each time the encryption value of same text should be generated same.

Suppose if I am encrypting a text "My Name is John". And while encrypting first time its value was generated kPddYx+eLwgK6CkJK1Vt2iGP8x8dv66YKz8YoHmfhrQ= then requirement is, if I am again encrypting the same text "My Name is John", It should generate the same encrypted string as the first one.

Muddassir Rahman
  • 976
  • 1
  • 9
  • 20
  • Use the same key every time? – derpirscher Jun 13 '22 at 14:33
  • Many encryptions add a really random _seed_ to generate a key. Providing the same seed would then ensure the same encryption. However that would often open some ways of attack, like with prefixes of the text. For a non-productive encryption you could use `text.hashCode()` as int seed. – Joop Eggen Jun 13 '22 at 14:34
  • @derpirscher Yes using the same key everytime – Muddassir Rahman Jun 13 '22 at 14:35
  • Well obviously you are not. If you are encrypting the same block of data with the same key, you will get the same result. Because, especially for a symmetric algorithm, how would you else be able to decrypt your data again? But as you don't show any code, nobody will be able to help you any further. The only advice one can give on that amout of information is: *Use the same key every time for encryption* – derpirscher Jun 13 '22 at 14:37
  • 1
    @derpirscher I have added sample code – Muddassir Rahman Jun 13 '22 at 14:48
  • 1
    The old XY problem popping up again. – President James K. Polk Jun 13 '22 at 15:13
  • 2
    Yes, but don't do it. The randomness of the ciphertext at constant key and plaintext is caused by a random IV and is intentional for security reasons. `Cipher#init()` generates a random IV each time (which can be retrieved with `getIV()`). Alternatively, a random IV can be explicitly generated and passed into `init()`. If a constant IV is applied here, this would result in a constant ciphertext, which is a common bug. – Topaco Jun 13 '22 at 18:13
  • @Topaco common bug? – kelalaka Jun 13 '22 at 20:34
  • @kelalaka - Well, yes, taking a static IV is what I would call a bug. And this happens quite often. – Topaco Jun 13 '22 at 20:43
  • @Topaco isn't this necessary for testing and verification? – kelalaka Jun 13 '22 at 20:49
  • @kelalaka - I'm referring to the *finished* implementation, this should not contain a static IV. For testing purposes this is OK. – Topaco Jun 13 '22 at 21:18

0 Answers0