- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试像这样在客户端加密字符串
public static void main(String[] args) throws Exception {
Client client = Client.create();
Form form = new Form();
String en = getRsaEcryptedData();
form.add("params", getRsaEcryptedData());
WebResource webResource = client.resource("http://localhost:8080/Server/request/data");
ClientResponse response = webResource.type(MediaType.APPLICATION_OCTET_STREAM).post(ClientResponse.class, form);
Reader r = new InputStreamReader(response.getEntityInputStream());
StringWriter sw = new StringWriter();
char[] buffer = new char[1024];
for (int n; (n = r.read(buffer)) != -1; )
sw.write(buffer, 0, n);
String str = sw.toString();
System.out.println(str);
}
private static String getRsaEcryptedData() {
AsymetricKeyCryptography ac = new AsymetricKeyCryptography();
String source = "helloworld";
return new String(ac.encrypt(source));
}
我正在尝试像这样在服务器端解密相同的内容。我正在使用 jersey 公开 Web 服务。
@POST
@Path("data")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public String getMsg(@FormParam("params") String params) {
System.out.println("params--> "+params);
return getRsaDecryptedData(params);
}
private static String getRsaDecryptedData(String data) {
AsymetricKeyCryptography ac = new AsymetricKeyCryptography();
return new String(ac.decrypt(data.getBytes()));
}
AysmetricKeyCryptography 类如下所示
public class AsymetricKeyCryptography {
public AsymetricKeyCryptography() {
super();
if (!areKeysPresent()) {
generateKey();
}
}
/**
* Generate key which contains a pair of private and public key using 1024
* bytes. Store the set of keys in Prvate.key and Public.key files.
*
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws FileNotFoundException
*/
public static void generateKey() {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(Constants.ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
File privateKeyFile = new File(Constants.PRIVATE_KEY_FILE);
File publicKeyFile = new File(Constants.PUBLIC_KEY_FILE);
//create the public and private key files
createPUBPRIVFiles(privateKeyFile,publicKeyFile);
// Saving the Public key in a file
saveKey(publicKeyFile,key,"public");
// Saving the Private key in a file
saveKey(privateKeyFile,key,"private");
} catch (Exception e) {
e.printStackTrace();
}
}
/** saves the keys in proper files
* @param keyFile
* @param key
* @param pub_priv_flag
*/
private static void saveKey(File keyFile, KeyPair key, String pub_priv_flag) {
try {
ObjectOutputStream keyOS = new ObjectOutputStream(new FileOutputStream(keyFile));
if(pub_priv_flag.equalsIgnoreCase("public")){
keyOS.writeObject(key.getPublic());
} else if(pub_priv_flag.equalsIgnoreCase("private")){
keyOS.writeObject(key.getPrivate());
}
keyOS.close();
}catch (Exception e) {
e.printStackTrace();
}
}
/**creates the public and private key files
* @param privateKeyFile
* @param publicKeyFile
*/
private static void createPUBPRIVFiles(File privateKeyFile, File publicKeyFile) {
try {
if (privateKeyFile.getParentFile() != null)
privateKeyFile.getParentFile().mkdirs();
privateKeyFile.createNewFile();
if (publicKeyFile.getParentFile() != null)
publicKeyFile.getParentFile().mkdirs();
publicKeyFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The method checks if the pair of public and private key has been generated.
*
* @return flag indicating if the pair of keys were generated.
*/
public static boolean areKeysPresent() {
File privateKey = new File(Constants.PRIVATE_KEY_FILE);
File publicKey = new File(Constants.PUBLIC_KEY_FILE);
if (privateKey.exists() && publicKey.exists()) {
return true;
}
return false;
}
/**
* Encrypt the plain text using public key.
*
* @param text
* @param key
*/
public static byte[] encrypt(String text) {
byte[] cipherText = null;
try {
ObjectInputStream inputStream = null;
// Encrypt the string using the public key
inputStream = new ObjectInputStream(new FileInputStream(Constants.PUBLIC_KEY_FILE));
final PublicKey key = (PublicKey) inputStream.readObject();
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(Constants.ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
/**
* Decrypt text using private key.
* @param text
* @param key
*/
public static String decrypt(byte[] text) {
byte[] dectyptedText = null;
try {
System.out.println("loading private key : "+Constants.PRIVATE_KEY_FILE);
ObjectInputStream inputStream = null;
inputStream = new ObjectInputStream(new FileInputStream(Constants.PRIVATE_KEY_FILE));
final PrivateKey key = (PrivateKey) inputStream.readObject();
final Cipher cipher = Cipher.getInstance(Constants.ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
}
当我在 AsymetricKeyCryptography 类中运行 main 方法时,我得到了正确的结果,但是当我通过发送加密字符串调用 Web 服务时,它会抛出异常:
javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:337)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:1922)
at AsymetricKeyCryptography.decrypt(AsymetricKeyCryptography.java:161)
at SecureService.getRsaDecryptedData(SecureService.java:34)
at SecureService.getMsg(SecureService.java:29)
我不明白我哪里出了问题
最佳答案
我怀疑当您通过 StringWriter 将数据传输并在 Jersey 中将其作为字符串读回时,您的数据会被损坏。它应该始终保持一个字节数组。尝试通过 ByteArrayOutputStream 写入它,并将其作为 byte[] 或 InputStream 绑定(bind)到 Jersey 方法。
关于java - 使用 Jersey 的客户端加密和服务器端解密不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18628072/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!