如何在Java中加密字符串我需要的是加密字符串,這將顯示在2D條形碼(PDF-417),所以當(dāng)有人有一個想法來掃描它將沒有任何可讀性。其他所需經(jīng)費:不應(yīng)該很復(fù)雜它不應(yīng)由RSA、PKI基礎(chǔ)設(shè)施、密鑰對等組成。它必須足夠簡單,以擺脫人們四處窺探,并易于解密,其他公司有興趣獲得這些數(shù)據(jù)。他們打電話給我們,我們告訴他們標(biāo)準(zhǔn)或給他們一些簡單的密鑰,然后可以用來解密。也許這些公司可以使用不同的技術(shù),所以最好堅持一些標(biāo)準(zhǔn),而這些標(biāo)準(zhǔn)并不與某些特殊的平臺或技術(shù)掛鉤。你有什么建議?是否有一些Java類正在執(zhí)行encrypt() & decrypt()在達(dá)到高安全標(biāo)準(zhǔn)的過程中沒有太多的復(fù)雜性?
3 回答

喵喔喔
TA貢獻(xiàn)1735條經(jīng)驗 獲得超5個贊
讓我們假設(shè)要加密的字節(jié)在
byte[] input;
byte[] keyBytes;byte[] ivBytes;
現(xiàn)在,您可以為您選擇的算法初始化密碼:
// wrap key data in Key/IV specs to pass to cipherSecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);// create the cipher with the algorithm you choose // see javadoc for Cipher class for more info, e.g.Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
加密應(yīng)該是這樣的:
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);byte[] encrypted= new byte[cipher.getOutputSize(input.length)]; int enc_len = cipher.update(input, 0, input.length, encrypted, 0);enc_len += cipher.doFinal(encrypted, enc_len);
解密如下:
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);byte[] decrypted = new byte[cipher.getOutputSize(enc_len)]; int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);dec_len += cipher.doFinal(decrypted, dec_len);

陪伴而非守候
TA貢獻(xiàn)1757條經(jīng)驗 獲得超8個贊
public class EncryptUtils { public static final String DEFAULT_ENCODING = "UTF-8"; static BASE64Encoder enc = new BASE64Encoder(); static BASE64Decoder dec = new BASE64Decoder(); public static String base64encode(String text) { try { return enc.encode(text.getBytes(DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { return null; } }//base64encode public static String base64decode(String text) { try { return new String(dec.decodeBuffer(text), DEFAULT_ENCODING); } catch (IOException e) { return null; } }//base64decode public static void main(String[] args) { String txt = "some text to be encrypted"; String key = "key phrase used for XOR-ing"; System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key))); String encoded = base64encode(txt); System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded))); System.out.print("XOR-ing back to original: " + xorMessage(txt, key)); } public static String xorMessage(String message, String key) { try { if (message == null || key == null) return null; char[] keys = key.toCharArray(); char[] mesg = message.toCharArray(); int ml = mesg.length; int kl = keys.length; char[] newmsg = new char[ml]; for (int i = 0; i < ml; i++) { newmsg[i] = (char)(mesg[i] ^ keys[i % kl]); }//for i return new String(newmsg); } catch (Exception e) { return null; } }//xorMessage}//class
添加回答
舉報
0/150
提交
取消