client端和server端进行通信,分别是Alice和Bob,Client端加密,用流传给Server端,server解密,整个过程模拟RSA加密解密,考虑保密性和完整性。
Alice用Bob公钥加密,bob这边用自己私钥解密,没问题,但是Alice用自己私钥加密,Bob用Alice公钥解密时候,就报错,BadPaddingException异常
最开始我是直接用cipher.dofinal的,出问题,以为是RSA 分组加密问题,后来找了分组加密的代码,还是不行,我感觉可能是流传递的问题,但是怎么也弄不出来,麻烦大家看看。Alice.javapackage RSA2;import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;public class Alice {
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
public static String ciphermode = "RSA/ECB/PSCS7Padding";

private static byte[] confidentiality(String message, Key publicKeyBob) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, Exception {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.ENCRYPT_MODE, publicKeyBob);

byte[] data = message.getBytes();
int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段加密
while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
        cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
    } else {
        cache = cipher.doFinal(data, offSet, inputLen - offSet);
    }
    out.write(cache, 0, cache.length);
    i++;
    offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
private static byte[] intergrity(String message, Key privateKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.ENCRYPT_MODE, privateKeyAlice);

byte[] data = message.getBytes();
int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段加密
while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
        cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
    } else {
        cache = cipher.doFinal(data, offSet, inputLen - offSet);
    }
    out.write(cache, 0, cache.length);
    i++;
    offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;


}
private static byte[] conAndInter(String message, Key publicKeyBob, Key privateKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.ENCRYPT_MODE, privateKeyAlice);
byte[] result=cipher.doFinal(message.getBytes("UTF-8"));

cipher.init(Cipher.ENCRYPT_MODE, publicKeyBob);
return cipher.doFinal(result);
}
public static void main(String[] args) throws Exception {
int port = 7999;
String host = "127.0.0.1";
Socket s = new Socket(host,port);

//Key Generator
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keypair = keyPairGenerator.generateKeyPair();
Key publicKeyAlice = keypair.getPublic();
Key privateKeyAlice = keypair.getPrivate();


FileOutputStream fos = new FileOutputStream("E:\\workspace2\\publicKeyAlice.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(publicKeyAlice);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream("E:\\workspace2\\publicKeyBob.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Key publicKeyBob =(Key)ois.readObject();
ois.close();
fis.close();


String message ="i wanner finish lab!";

byte[] result = null;
switch(2)
{
case 1: 
result = confidentiality(message,publicKeyBob);
break;
case 2:
result = intergrity(message,privateKeyAlice);
break;
case 3:
result = conAndInter(message,publicKeyBob,privateKeyAlice);
}


DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeInt(result.length);
dos.write(result, 0, result.length);
System.out.println(new String(result));
// bw.write(bytesToString(result));
System.out.println("finished");
dos.close();
} }
Bob.class (帖子有字数限制,bob的包不打出来了)
package RSA2;
public class Bob {
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
public static String ciphermode = "RSA/ECB/PSCS7Padding"; private static byte[] confidentiality(byte[] encryptedData, Key privateKeyBob) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, Exception {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.DECRYPT_MODE, privateKeyBob);

        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData; }
private static byte[] intergrity(byte[] encryptedData, Key publicKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {

Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.DECRYPT_MODE, publicKeyAlice);

        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData; }
private static byte[] conAndInter(byte[] encryptedData, Key publicKeyAlice, Key privateKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.DECRYPT_MODE, publicKeyAlice);

//cipher.update(input, output)
byte[] result = cipher.doFinal();
return result;
}
private static byte[] stringToByte(String message){
        String[] strArr = message.split(" ");
        int len = strArr.length;
        byte[] clone = new byte[len];
        for (int i = 0; i < len; i++) {
            clone[i] = Byte.parseByte(strArr[i]);
        }
return clone;
}

public static void main(String[] args) throws Exception {
int port = 7999;
ServerSocket server = new ServerSocket(port);

//Key Generation
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keypair = keyPairGenerator.generateKeyPair();
Key publicKeyBob = keypair.getPublic();
Key privateKeyBob = keypair.getPrivate();

FileOutputStream fos = new FileOutputStream("E:\\workspace2\\publicKeyBob.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(publicKeyBob);
oos.close();
fos.close();
//System.out.println("have writen bob's publickey ");

System.out.println("waiting for connection ");
Socket s = server.accept();
System.out.println("conntect successfully ");

FileInputStream fis = new FileInputStream("E:\\workspace2\\publicKeyAlice.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Key publicKeyAlice =(PublicKey)ois.readObject();
ois.close();
fis.close(); //读内容
DataInputStream dis = new DataInputStream(s.getInputStream());
int len = dis.readInt();
byte[] encryptedData = new byte[len];
dis.read(encryptedData, 0, len);


//Decryption
byte[] result= null;
switch(2)
{

case 1:
result = confidentiality(encryptedData,privateKeyBob);
break;
case 2:
result = intergrity(encryptedData,publicKeyAlice);
break;
// case 3:
// result = conAndInter(message,privateKeyBob,publicKeyAlice,cipher);
}

System.out.println("Decrypted message: "+new String(result,"UTF-8"));
}
}