我有个问题。我正在尝试用RSA加密来编写一个安全的聊天服务器。我试图进行双重加密,这样每个客户端都知道消息只能来自其他客户端,并且它们是唯一能够读取消息的客户端。问题是,当我试图双重加密一个字符的长消息时,得到的第一个加密字节数组有256个字节长,当然,你不能用另一个密钥第二次加密,因为它太长了。我的问题是,如何使用下面的代码进行双重加密?理论上,我生成两个单独的密钥对,然后用一个公钥加密一个字符串,然后用另一个密钥加密一个字符串,反之亦然。相信我我试过了。
package client.crypto;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
public class CryptoUtils {
private static final String ALGORITHM = "RSA";
public static KeyPair getKeyPair() {
KeyPairGenerator keyGen = null;
try {
keyGen = KeyPairGenerator.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyGen.initialize(2048);
final KeyPair key = keyGen.generateKeyPair();
return key;
}
public static byte[] encrypt(String text, Key key) {
byte[] cipherText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
public static String decrypt(String text, Key key) {
byte[] dectyptedText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text.getBytes());
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
public static byte[] decryptToBytes(String text, Key key) {
byte[] dectyptedText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text.getBytes());
} catch (Exception ex) {
ex.printStackTrace();
}
return dectyptedText;
}
public static byte[] encrypt(byte[] bytes, Key key) {
byte[] cipherText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
public static String decrypt(byte[] bytes, Key key) {
byte[] dectyptedText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(bytes);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
public static byte[] decryptToBytes(byte[] bytes, Key key) {
byte[] dectyptedText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(bytes);
} catch (Exception ex) {
ex.printStackTrace();
}
return dectyptedText;
}
}发布于 2015-11-24 04:05:06
您的需求是合理的,但您提出的解决方案从根本上讲是有缺陷的,应该被放弃。
您应该回到您的需求,并寻求实现这些需求使用标准技术和API。
你不应该试图发明你自己的密码学方法。这是很难得到正确的,你更有可能创建一个真正安全的系统,如果你遵循标准的做法。关于如何处理您的需求的一些想法:
正如您已经发现的,RSA对于加密相对较少的数据是很好的。我还将注意到,使用RSA加密比使用对称算法(如AES )加密要慢得多。几十年来,加密界一直致力于提出安全和高效的解决方案,例如利用对称加密(例如AES)的性能,同时拥有非对称加密(例如RSA)的信任模式(无共享秘密)。
https://stackoverflow.com/questions/33884538
复制相似问题