java - Encrypt data in windows phone 8 using AES if I already have the key (as a string) -


i working on wp8 app requires encryption , decryption. need way encrypt data using aes. have key(as string). need c# equivalent below java code can help?

public static string encryptwithaes(string payload, string aeskey) {      byte[] raw = aeskey.getbytes();     secretkeyspec skeyspec = new secretkeyspec(raw, "aes/ecb/pkcs5padding");     try {         cipher cipher = cipher.getinstance("aes/ecb/pkcs5padding");         cipher.init(cipher.encrypt_mode, skeyspec);          byte[] encrypted;         encrypted = cipher.dofinal(payload.getbytes());         cipher = null;         return base64.encodetostring(encrypted, base64.default);     } catch (exception e) {         system.out.println("error in encryptwithaes!!!");         e.printstacktrace();     }     return null; } 

here did :

public static byte[] encryptwithaes(string datatoencrypt, string key)     {          byte[] encrypteddata;          byte[] keybytes = system.text.encoding.utf8.getbytes(key);           using (aesmanaged aesenc = new aesmanaged())         {             aesenc.key = keybytes;             aesenc.iv = new byte[16];              //create encryptor converting             icryptotransform encryptor = aesenc.createencryptor(aesenc.key, aesenc.iv);               using (memorystream memstream = new memorystream())             {                 using (cryptostream crypstream = new cryptostream(memstream, encryptor, cryptostreammode.write))                 {                     using (streamwriter srmwriter= new streamwriter(crypstream))                     {                          srmwriter.write(datatoencrypt);                     }                     encrypteddata = memstream.toarray();                 }             }         }         return encrypteddata;     } 

the error getting set key: ie aesenc.key= keybytes;

your c# code works fine. write, "the error getting set key: ie aesenc.key= keybytes;" don't mention error is. guess getting cryptographic exception message, "specified key not valid size algorithm."

as experiment, try this:

byte[] output = encryptwithaes("hello", encoding.utf8.getstring(new byte[16])); 

or

byte[] output = encryptwithaes("hello", encoding.utf8.getstring(new byte[32])); 

and see if still error setting key. is, make sure key string produces array of either 16 or 32 bytes.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -