Android ArrayIndexOutOfBounds 中的 RSA 加密

发布于 2024-11-16 07:09:34 字数 5607 浏览 1 评论 0原文

我正在尝试在 Android 上进行 RSA 加密,我从这里开始遵循 RSA 指南: http: //www.javamex.com/tutorials/cryptography/rsa_encryption.shtml

我稍微修改了代码,这是我的代码:

Button GenKey = null;
Button encryptString = null;
Button decryptString = null;
EditText plainField = null;
EditText encryptedField = null;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GenKey = (Button) findViewById(R.id.btnGenKey);
    GenKey.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
                generateKey();
        }
    });

    encryptString = (Button) findViewById(R.id.btnEncrypt);
    encryptString.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            byte[] encryptedData = null;
            byte[] dataToEncrypt = null;
            plainField = (EditText) findViewById (R.id.eTxtPlainTxt);
            String plainText = plainField.getText().toString();
                dataToEncrypt = plainText.getBytes("UTF-8");
                encryptedData = rsaEncrypt(dataToEncrypt);              
            String encryptedText=null;
                encryptedText = new String(encryptedData, "UTF-8");
            encryptedField = (EditText)findViewById(R.id.eTxtCiphTxt);
            encryptedField.setText(encryptedText);
        }
    });

    decryptString = (Button) findViewById(R.id.btnDecrypt);
    decryptString.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            byte[] decryptedData = null;
            byte[] dataToEncrypt = null;
            encryptedField = (EditText) findViewById (R.id.eTxtCiphTxt);
            String cipherText = encryptedField.getText().toString();    
                dataToEncrypt = cipherText.getBytes("UTF-8");
                decryptedData = rsaDecrypt(dataToEncrypt);

            String decryptedText = null;
                decryptedText = new String(decryptedData,"UTF-8");
            plainField = (EditText)findViewById(R.id.eTxtPlainTxt);
            plainField.setText(decryptedText);
        }
    });

}//end of onCreate

public void generateKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException{
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512);
    KeyPair kp = kpg.genKeyPair();

    KeyFactory fact = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
    RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);

    saveToFile("public.key", pub.getModulus(),pub.getPublicExponent());
    saveToFile("private.key", priv.getModulus(),priv.getPrivateExponent());
    }//end of generateKey

public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {        
    FileOutputStream fOutStream = openFileOutput(fileName, MODE_PRIVATE);
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fOutStream));
    oos.writeObject(mod);
    oos.writeObject(exp);
    oos.flush();
    oos.close();
    }//end of saveToFile

public PublicKey readPubKeyFromFile(String keyFileName) throws StreamCorruptedException, IOException{
    FileInputStream fInStream = openFileInput(keyFileName);
    ObjectInputStream oInStream = new ObjectInputStream(new BufferedInputStream(fInStream));
        BigInteger m = (BigInteger) oInStream.readObject();
        BigInteger e = (BigInteger) oInStream.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pubKey = fact.generatePublic(keySpec);
        return pubKey;
        oInStream.close();
}//end of readPubKeyFromFile

public PrivateKey readPrivKeyFromFile(String keyFileName) throws StreamCorruptedException, IOException{
    FileInputStream fInStream = openFileInput(keyFileName);
    ObjectInputStream oInStream = new ObjectInputStream(new BufferedInputStream(fInStream));
        BigInteger m = (BigInteger) oInStream.readObject();
        BigInteger e = (BigInteger) oInStream.readObject();
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PrivateKey privKey = fact.generatePrivate(keySpec);
        return privKey;
        oInStream.close();
}//end of readPubKeyFromFile

public byte[] rsaEncrypt(byte[] data) throws StreamCorruptedException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    PublicKey pubKey = readPubKeyFromFile("public.key");
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] cipherData = cipher.doFinal(data);
    return cipherData;    
}//end of rsaEncrypt

public byte[] rsaDecrypt(byte[] data) throws StreamCorruptedException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
    PrivateKey privKey = readPrivKeyFromFile("private.key");
    Cipher decipher = Cipher.getInstance("RSA");
    decipher.init(Cipher.DECRYPT_MODE, privKey);
    byte[] plainData = decipher.doFinal(data);
    return plainData;   
}

问题是当我加密字符串时,它显示一些随机字符符号,例如如 €◊•¶⓿ 等... 另一个问题是,当我尝试解密它时,它在解密部分的 doFinal 处抛出 ArrayIndexOutOfBoundsException 。

问题出在哪里?

i am trying to do RSA encryption on Android, i followed the guide on RSA from here: http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml

i modified the code a bit, and here is my code:

Button GenKey = null;
Button encryptString = null;
Button decryptString = null;
EditText plainField = null;
EditText encryptedField = null;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GenKey = (Button) findViewById(R.id.btnGenKey);
    GenKey.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
                generateKey();
        }
    });

    encryptString = (Button) findViewById(R.id.btnEncrypt);
    encryptString.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            byte[] encryptedData = null;
            byte[] dataToEncrypt = null;
            plainField = (EditText) findViewById (R.id.eTxtPlainTxt);
            String plainText = plainField.getText().toString();
                dataToEncrypt = plainText.getBytes("UTF-8");
                encryptedData = rsaEncrypt(dataToEncrypt);              
            String encryptedText=null;
                encryptedText = new String(encryptedData, "UTF-8");
            encryptedField = (EditText)findViewById(R.id.eTxtCiphTxt);
            encryptedField.setText(encryptedText);
        }
    });

    decryptString = (Button) findViewById(R.id.btnDecrypt);
    decryptString.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            byte[] decryptedData = null;
            byte[] dataToEncrypt = null;
            encryptedField = (EditText) findViewById (R.id.eTxtCiphTxt);
            String cipherText = encryptedField.getText().toString();    
                dataToEncrypt = cipherText.getBytes("UTF-8");
                decryptedData = rsaDecrypt(dataToEncrypt);

            String decryptedText = null;
                decryptedText = new String(decryptedData,"UTF-8");
            plainField = (EditText)findViewById(R.id.eTxtPlainTxt);
            plainField.setText(decryptedText);
        }
    });

}//end of onCreate

public void generateKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException{
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512);
    KeyPair kp = kpg.genKeyPair();

    KeyFactory fact = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
    RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);

    saveToFile("public.key", pub.getModulus(),pub.getPublicExponent());
    saveToFile("private.key", priv.getModulus(),priv.getPrivateExponent());
    }//end of generateKey

public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {        
    FileOutputStream fOutStream = openFileOutput(fileName, MODE_PRIVATE);
    ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fOutStream));
    oos.writeObject(mod);
    oos.writeObject(exp);
    oos.flush();
    oos.close();
    }//end of saveToFile

public PublicKey readPubKeyFromFile(String keyFileName) throws StreamCorruptedException, IOException{
    FileInputStream fInStream = openFileInput(keyFileName);
    ObjectInputStream oInStream = new ObjectInputStream(new BufferedInputStream(fInStream));
        BigInteger m = (BigInteger) oInStream.readObject();
        BigInteger e = (BigInteger) oInStream.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pubKey = fact.generatePublic(keySpec);
        return pubKey;
        oInStream.close();
}//end of readPubKeyFromFile

public PrivateKey readPrivKeyFromFile(String keyFileName) throws StreamCorruptedException, IOException{
    FileInputStream fInStream = openFileInput(keyFileName);
    ObjectInputStream oInStream = new ObjectInputStream(new BufferedInputStream(fInStream));
        BigInteger m = (BigInteger) oInStream.readObject();
        BigInteger e = (BigInteger) oInStream.readObject();
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PrivateKey privKey = fact.generatePrivate(keySpec);
        return privKey;
        oInStream.close();
}//end of readPubKeyFromFile

public byte[] rsaEncrypt(byte[] data) throws StreamCorruptedException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    PublicKey pubKey = readPubKeyFromFile("public.key");
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] cipherData = cipher.doFinal(data);
    return cipherData;    
}//end of rsaEncrypt

public byte[] rsaDecrypt(byte[] data) throws StreamCorruptedException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
    PrivateKey privKey = readPrivKeyFromFile("private.key");
    Cipher decipher = Cipher.getInstance("RSA");
    decipher.init(Cipher.DECRYPT_MODE, privKey);
    byte[] plainData = decipher.doFinal(data);
    return plainData;   
}

the problem is when i encrypt the string, it displays some random characters symbol such as €◊•¶⓿ etc...
another problem is, when i try to decrypt it, it throws an ArrayIndexOutOfBoundsException at the doFinal on the decryption part..

where is the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文