how to encrypt cookies as it accepts only US-ASCII characters? when i use below code, it generates characters out of US_ASCII. how to limit encrypted characters not to go out of US_ASCII?
key = KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance("DESede");
messageSource.getMessage("encryption.algorithm",null,localeUtil.getLocale(开发者_如何学Go));
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] outputBytes = cipher.doFinal(input.getBytes());
Firstly: don't use String.getBytes
without specifying an encoding, preferably something which can handle all of Unicode, such as UTF-8.
Secondly: the code you've given doesn't generate characters at all - it generates bytes. You mustn't treat those bytes as if they're encoded text - they're not. Instead, you should convert them to base64, e.g. with Apache Commons Codec or this public domain code.
Then when you need to decrypt, you simply reverse all the steps - convert back from base64 to binary, decrypt, and then create a string with new String(decryptedBytes, "UTF-8")
(or whatever encoding you decided to use).
public static final String CHARSET = "ISO-8859-1";
String text = "Ángel";
String encodedText = new String(Base64.encodeBase64(text.getBytes(CHARSET)));
String decodedText = new String(Base64.decodeBase64(encodedText.getBytes(CHARSET)))
In addition to Jon's answer, you can view the available encodings here: http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html
精彩评论