如何在Java中加密字符串我需要的是加密字符串,这将显示在2D条形码(PDF-417),所以当有人有一个想法来扫描它将没有任何可读性。其他所需经费:不应该很复杂它不应由RSA、PKI基础设施、密钥对等组成。它必须足够简单,以摆脱人们四处窥探,并易于解密,其他公司有兴趣获得这些数据。他们打电话给我们,我们告诉他们标准或给他们一些简单的密钥,然后可以用来解密。也许这些公司可以使用不同的技术,所以最好坚持一些标准,而这些标准并不与某些特殊的平台或技术挂钩。你有什么建议?是否有一些Java类正在执行encrypt() & decrypt()在达到高安全标准的过程中没有太多的复杂性?
3 回答

喵喔喔
TA贡献1735条经验 获得超5个赞
让我们假设要加密的字节在
byte[] input;
byte[] keyBytes;byte[] ivBytes;
现在,您可以为您选择的算法初始化密码:
// 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");
加密应该是这样的:
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贡献1757条经验 获得超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
提交
取消