quocvuongdn icon

#Java: #RC4 + Base64

quocvuongdn | PRO | 12/26/14 02:50:39 AM UTC | 0 ⭐ | 538 👁️ | Never ⏰ | []
Java |

910 B

|

None

|

0 👍

/

0 👎

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
/*...*/
 
public static String encrypt(String key, String clearText) throws Exception{         
    Cipher c = Cipher.getInstance(RC4_NAME);
    Key mainKey = new SecretKeySpec(key.getBytes(), "RC4");
    c.init(Cipher.ENCRYPT_MODE, mainKey);
    byte[] encVal = c.doFinal(clearText.getBytes(UNICODE));         
    String encryptedValue =  Base64.encodeToString(encVal, false);
    return encryptedValue;         
}
 
public static String decrypt(String key, String encryptedData) throws Exception {       
    Cipher c = Cipher.getInstance(RC4_NAME);
    Key mainKey = new SecretKeySpec(key.getBytes(), "RC4");
    c.init(Cipher.DECRYPT_MODE, mainKey);
    byte[] decordedValue = Base64.decode(encryptedData);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue, UNICODE);        
    return decryptedValue;        
}

Comments