Ran*_*uve 6 java string encryption cryptography
我正在制作一个简单的程序,它在文本框中输入文本,并获取另一个文本框中的密码,然后对其进行某种简单加密并将其保存到文件中.之后,用户应该能够再次打开文件并提供用于加密的密码,并且应该吐出原始文本.
现在我正在拿绳子.将其分隔为char数组,然后对密码执行相同操作.之后,我获取密码,将所有这些字符转换为整数,找到所有字符的平均值,并将其用作原始文本中字符的偏移量.有一些像:
textChars[1]= (char)((int)textChars[1]+offset);
Run Code Online (Sandbox Code Playgroud)
然后我可以反过来加密字符串:
encryptedChars[1]= (char)((int)encryptedChars[1]-offset);
Run Code Online (Sandbox Code Playgroud)
问题是字符在不同平台上具有不同的值,因此有时偏移会将字符变成一些疯狂的数字(如负值),这只会将字符变成问号.
我查看了标准Java API中的加密库,但是如果每次启动程序时随机生成密钥,我会感到困惑.
我需要的是两个函数,它们看起来像是String encrypt(String text,String Password)用密码加密的文本作为解密它的密钥,并且String decrypt(String encryptedText, String Password)会吐出原始文本(如果密码是垃圾则会乱码)
任何帮助都非常感谢,这实际上只是一个个人项目,所以我不需要任何花哨的加密方法.
Aks*_*hay 11
你正试图重新发明轮子.除非你是为了好玩,否则我建议使用像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;
}
Run Code Online (Sandbox Code Playgroud)
您可能希望改进此代码.
您真正需要的是对称加密,即该算法使用相同的密钥来加密和解密数据.有许多可用的算法支持对称加密,如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 };
Run Code Online (Sandbox Code Playgroud)
同
byte[] keyBytes = yourPassword.getBytes();
Run Code Online (Sandbox Code Playgroud)
它使用了bouncycastle库,它可以说是最好的加密库.