php - sending rc4 encrypted api call in java -


i trying make api call in java using these steps:

  1. json encode
  2. rc4 encryption
  3. base64 encoding

i using same system in php , working correctly:

$enc_request = base64_encode(openssl_encrypt(json_encode($request_params), "rc4", $this->_app_key)); 

but when use same system in java, results not expected. here's code:

//json encoding jsonobject obj = new jsonobject(); obj.put("email", username); obj.put("password", password); obj.put("action", "login");  //function encode base64 private string getbase64encoded(string encryptedjsonstring) {     byte[] encoded = base64.encodebase64(encryptedjsonstring.getbytes());      string encodedstring = new string(encoded);      return encodedstring; }  //function encrypt in rc4 private string getrc4encryptedstring2(string string, string key) throws exception {     cipher cipher = cipher.getinstance("rc4");     secretkeyspec rc4key = new secretkeyspec(key.getbytes(), "rc4");     cipher.init(cipher.encrypt_mode, rc4key);      byte[] ciphertext = cipher.update(string.getbytes());      return new string(ciphertext); } 

i able identify problem upto rc4 encryption not returning same result php version.

i've been battling 2 days now. hope have not missed stupid thing because should straight-forward.

thanks

you should use byte[] not string hold intermediate byte array values. string text, not raw data, , attempt decode bytes character data using system's default character set (at least, single-parameter string constructor will). same string.getbytes().

just return ciphertext directly getrc4encryptedstring2(), , pass directly getbase64encoded(). there's reason encoders operate on byte arrays, , reason not can garble data applying character encoding in between.

the same goes key passing getrc4encryptedstring2(). @ bare minimum use string.getbytes("iso-8859-1") or (assuming key text , not yet garbled byte array). no-parameter version of getbytes() returns text encoded using system's default character set, not guaranteed want.

that applies string returning base 64 encoder. don't know base 64 encoder using, make sure specify character set string constructor. ok, purely coincidence, should always specify character set when converting to/from string , raw bytes. , that, of course, assumes base 64 encoder returns text, rather bytes in range 0-63.

the general point here can't convert , forth string byte[]. string text , it's representation byte[] depends on character encoding.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -