找不到符号Java初始化RSA

找不到符号Java初始化RSA,java,exception-handling,cryptography,rsa,Java,Exception Handling,Cryptography,Rsa,您好,我想运行以下命令 // Initialise the RSA cipher with PUBLIC key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); 但是我有以下错误,在Cipher Cipher=Cipher.init(Cipher.ENCRYPT_MODE,keyPair.getPublic())中

您好,我想运行以下命令

// Initialise the RSA cipher with PUBLIC key
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
但是我有以下错误,在Cipher Cipher=Cipher.init(Cipher.ENCRYPT_MODE,keyPair.getPublic())中找不到任何符号

以下是我导入的以下软件包:

import java.net.*; 
import java.io.*; 
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import sun.misc.*;
import java.io.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.lang.Exception;
以下是作为接收传入连接的服务器的完整代码。在接受连接后,它将生成一个AES密钥和一个RSA密码,用于加密密钥

import java.net.*; 
import java.io.*; 
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import sun.misc.*;
import java.io.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.lang.Exception;

public class Server { 
  public static void main (String [] args ) throws IOException { 
    ServerSocket serverSocket = new ServerSocket(15123); 
    Socket socket = serverSocket.accept(); 
    System.out.println("Accepted connection : " + socket); 

    System.out.println("A Simple Program using RSA to encrypt a single symmetric key using");
    System.out.println("Advanced Encryption Standard (AES).\n");
    System.out.println("Generating a symmetric (AES) key...");
    try{
      KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
      keyGenerator.init(128);
      Key AESKey = keyGenerator.generateKey();
      System.out.println("Format: "+AESKey.getFormat());
    } catch (Exception e){
      System.out.println("WRONG!");
    }

    // Create an RSA key pair
    System.out.println("Generating an RSA key...");
    try{
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(1024);
      // Insert your statement here
      KeyPair keyPair = keyPairGenerator.genKeyPair();
      System.out.println(keyPair.getPublic().getFormat());
      System.out.println(keyPair.getPrivate().getFormat());
      String publicKeyFilename = "public";

      byte[] publicKeyBytes = keyPair.getPublic().getEncoded();

      X509EncodedKeySpec x509Encoded = new X509EncodedKeySpec(publicKeyBytes);
      FileOutputStream fos = new FileOutputStream(publicKeyFilename);
      fos.write(x509Encoded.getEncoded());
      fos.close();

      String privateKeyFilename = "privateKeyFilename";

      byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();

      //byte[] encryptedPrivateKeyBytes = passwordEncrypt(password.toCharArray(), privateKeyBytes);
      PKCS8EncodedKeySpec pkcs8Encoded = new PKCS8EncodedKeySpec(privateKeyBytes);
      fos = new FileOutputStream(privateKeyFilename);
      fos.write(pkcs8Encoded.getEncoded());
      fos.close();

      System.out.println("Done generating the key.\n");
    } catch (Exception e){
      System.out.println("WRONG!");
    }

    // Initialise the RSA cipher with PUBLIC key
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    // Insert your statement here
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());

    // Get the bytes of the AES key
    byte[] encryptedKey = AESKey.getEncoded();
    System.out.println("AES key:\n" + asHex(encryptedKey) + "\n");

    // Perform the actual encryption on those bytes
    byte[] cipherText = cipher.doFinal(encryptedKey);
    System.out.println("Encrypted key:\n" + asHex(cipherText) + "\n");

    File transferFile = new File ("copy.doc"); 
    byte [] bytearray = new byte [(int)transferFile.length()]; 
    FileInputStream fin = new FileInputStream(transferFile); 
    BufferedInputStream bin = new BufferedInputStream(fin); 
    bin.read(bytearray,0,bytearray.length); 
    OutputStream os = socket.getOutputStream(); 
    System.out.println("Sending Files..."); 
    os.write(bytearray,0,bytearray.length); 
    os.flush(); 
    socket.close(); 
    System.out.println("File transfer complete"); 
  } 

  public static String asHex (byte buf[]) {

    //Obtain a StringBuffer object
    StringBuffer strbuf = new StringBuffer(buf.length * 2);
    int i;

    for (i = 0; i < buf.length; i++) {
      if (((int) buf[i] & 0xff) < 0x10)
        strbuf.append("0");
      strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
    }
    // Return result string in Hexadecimal format
    return strbuf.toString();
  }
}
import java.net.*;
导入java.io.*;
导入javax.crypto.*;
导入javax.crypto.spec.*;
导入java.security.*;
导入sun.misc.*;
导入java.io.*;
导入java.security.spec.PKCS8EncodedKeySpec;
导入java.security.spec.X509EncodedKeySpec;
导入java.lang.Exception;
公共类服务器{
公共静态void main(字符串[]args)引发IOException{
ServerSocket ServerSocket=新的ServerSocket(15123);
Socket=serverSocket.accept();
System.out.println(“接受的连接:+插座”);
println(“一个使用RSA加密单个对称密钥的简单程序”);
System.out.println(“高级加密标准(AES)。\n”);
System.out.println(“生成对称(AES)密钥…”);
试一试{
KeyGenerator KeyGenerator=KeyGenerator.getInstance(“AES”);
密钥生成器init(128);
Key AESKey=keyGenerator.generateKey();
System.out.println(“格式:+AESKey.getFormat());
}捕获(例外e){
System.out.println(“错误!”);
}
//创建RSA密钥对
System.out.println(“生成RSA密钥…”);
试一试{
KeyPairGenerator KeyPairGenerator=KeyPairGenerator.getInstance(“RSA”);
keyPairGenerator.initialize(1024);
//在这里插入您的声明
KeyPair KeyPair=keyPairGenerator.genKeyPair();
System.out.println(keyPair.getPublic().getFormat());
System.out.println(keyPair.getPrivate().getFormat());
字符串publicKeyFilename=“public”;
byte[]publicKeyBytes=keyPair.getPublic().getEncoded();
X509EncodedKeySpec x509Encoded=新的X509EncodedKeySpec(publicKeyBytes);
FileOutputStream fos=新的FileOutputStream(publicKeyFilename);
fos.write(x509Encoded.getEncoded());
fos.close();
字符串privateKeyFilename=“privateKeyFilename”;
byte[]privateKeyBytes=keyPair.getPrivate().getEncoded();
//byte[]encryptedPrivateKeyBytes=密码加密(password.tocharray(),privateKeyBytes);
PKCS8EncodedKeySpec pkcs8Encoded=新的PKCS8EncodedKeySpec(privateKeyBytes);
fos=新文件输出流(privateKeyFilename);
fos.write(pkcs8Encoded.getEncoded());
fos.close();
System.out.println(“生成密钥完成。\n”);
}捕获(例外e){
System.out.println(“错误!”);
}
//使用公钥初始化RSA密码
Cipher Cipher=Cipher.getInstance(“RSA/ECB/PKCS1Padding”);
//在这里插入您的声明
init(cipher.ENCRYPT_模式,keyPair.getPublic());
//获取AES密钥的字节数
字节[]encryptedKey=AESKey.getEncoded();
System.out.println(“AES密钥:\n”+asHex(加密密钥)+”\n”);
//对这些字节执行实际加密
字节[]密文=cipher.doFinal(encryptedKey);
System.out.println(“加密密钥:\n”+asHex(密文)+”\n”);
文件传输文件=新文件(“copy.doc”);
byte[]bytearray=新字节[(int)transferFile.length()];
FileInputStream fin=新的FileInputStream(传输文件);
BufferedInputStream bin=新的BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os=socket.getOutputStream();
System.out.println(“发送文件…”);
写操作(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println(“文件传输完成”);
} 
公共静态字符串asHex(字节buf[]{
//获取StringBuffer对象
StringBuffer strbuf=新的StringBuffer(buf.length*2);
int i;
对于(i=0;i

请帮忙

变量密钥对的声明在try块中完成。所以变量密钥对的作用域就是这个块。在块外部调用cipher.init,因此此块中不存在变量keypPair

解决方案在尝试块之前,请添加:

KeyPair keypair = null;
然后只需将try块中的值关联起来就可以了。答案确实是在
try/catch
之前声明变量。但是,无需使用
null
对其进行初始化。相反,只需使错误处理更加具体:

final KeyPair keyPair;
try {
    ...
    keyPair = keyPairGenerator.genKeyPair();
    ...
} catch(final Exception e) {
    throw new RuntimeException("Exception during key pair generation not handled", e);
}
...
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
...
现在,由于您正在抛出一个
RuntimeException
,编译器知道永远不会到达
init
语句,因此不需要为
keyPair
变量赋值。如果没有异常,那么
密钥对
现在已声明并初始化,您将不再获得编译时错误

当然,在最后的代码中,您希望计算出您想要捕获的确切异常以及如何处理它们。此时,您应该根据程序状态和编程错误/运行时错误以不同的方式处理异常



{
}
之间声明的任何内容在
}
之后变为超出范围。没有太多使用,但您甚至可以使用
{
}
(没有
if
while
)来定义新的范围。这在
switch
/
case
构造或测试期间非常有用,因为如果不引入新范围,可能会出现名称冲突。

请提供准确的错误。我想是编译时吧?您是否正确设置了
import
语句