如何使用另一个字符串作为密码加密/解密字符串?

我正在制作一个简单的程序,它在文本框中输入文本,并获取另一个文本框中的密码,然后对其进行某种简单加密并将其保存到文件中。 之后,用户应该能够再次打开文件并提供用于加密的密码,并且应该吐出原始文本。

现在我正在拿绳子。 将其分隔为char数组,然后对密码执行相同操作。 之后,我获取密码,将所有这些字符转换为整数,找到所有字符的平均值,并将其用作原始文本中字符的偏移量。 有一些像:

textChars[1]= (char)((int)textChars[1]+offset); 

然后我可以反过来加密字符串:

 encryptedChars[1]= (char)((int)encryptedChars[1]-offset); 

问题是字符在不同的平台上有不同的值,所以有时偏移会将字符变成一些疯狂的数字(如负值),这只会将字符变成问号。

我查看了标准Java API中的加密库,但是如果密钥只是在每次启动程序时随机生成,我会感到困惑。

我需要的是两个看起来像String encrypt(String text,String Password)函数String encrypt(String text,String Password) ,它将用密码加密的文本作为解密它的密钥,以及String decrypt(String encryptedText, String Password)将吐出原始函数文字(如果密码是垃圾,则为乱码)

任何帮助都非常感谢,这实际上只是一个个人项目,所以我不需要任何花哨的加密方法。

您真正需要的是对称加密,即该算法使用相同的密钥来加密和解密数据。 有许多可用的算法支持对称加密,如DES,AES。

看一下这个例子: http : //www.java2s.com/Code/Java/Security/EncryptionanddecryptionwithAESECBPKCS7Padding.htm

在上面的例子中,替换

 byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; 

 byte[] keyBytes = yourPassword.getBytes(); 

它使用了bouncycastle库,它可以说是最好的加密库。

你正试图重新发明轮子。 除非你是为了好玩,否则我建议使用像AES这样的东西。 如果你只是google“AES in java”,你会发现很多例子。

如果你是为了好玩而想要实现简单的东西,那么也要看看ROT13 。

以下是Java中的AES示例:

 private static final String ALGORITHM = "AES"; private static final byte[] keyValue = new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' }; public String encrypt(String valueToEnc) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, key); byte[] encValue = c.doFinal(valueToEnc.getBytes()); String encryptedValue = new BASE64Encoder().encode(encValue); return encryptedValue; } public String decrypt(String encryptedValue) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.DECRYPT_MODE, key); byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue); byte[] decValue = c.doFinal(decordedValue); String decryptedValue = new String(decValue); return decryptedValue; } private static Key generateKey() throws Exception { Key key = new SecretKeySpec(keyValue, ALGORITHM); return key; } 

您可能希望改进此代码。