Android 中的字符串加密

2024-05-10

我正在使用代码进行加密和加密。它没有给出字符串结果。字节数组未转换为字符串。我几乎尝试了所有方法将字节数组转换为字符,但没有给出结果。

   public class EncryptionTest extends Activity {

EditText input, output, outputDecrypt;
String plain_text;
byte[] key, encrypted_bytes,keyStart,byte_char_text,decrpyted_bytes ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_encryption_test);

    input = (EditText) findViewById(R.id.text_inputText);
    output = (EditText) findViewById(R.id.text_Result);
    outputDecrypt = (EditText) findViewById(R.id.text_decrypt_Result);
    Button encrypt_btn = (Button) findViewById(R.id.btn_encrpyt);
    Button decrypt_btn = (Button) findViewById(R.id.btn_Decrypt);

    plain_text = input.getText().toString();
    keyStart = "Supriyo".getBytes();
    byte_char_text = plain_text.getBytes();

    encrypt_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {


            try {

            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
                sr.setSeed(keyStart);
                keygen.init(128, sr);
                SecretKey skey = keygen.generateKey();
                key = skey.getEncoded();

                encrypted_bytes = encrypt(key, byte_char_text);
                String inputResult = encrypted_bytes.toString();
                output.setText(inputResult);
        decrpyted_bytes = decrypt(key, encrypted_bytes);
                     System.out.println("decr"+Arrays.toString(decrpyted_bytes));                                               
            String outputResult = new String(decrpyted_bytes,"UTF-8");
                System.out.println("-->>>"+outputResult);
                outputDecrypt.setText(outputResult);

            } catch (NoSuchAlgorithmException e) {

                e.printStackTrace();
            } catch (InvalidKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadPaddingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
        }

public static byte[] decrypt(byte[] raw, byte[] encrypteds)
        throws Exception          {

    SecretKeySpec skey = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skey);
    byte[] decrypted = cipher.doFinal(encrypteds);
    return decrypted;
}

public static byte[] encrypt(byte[] raw, byte[] clear)
        throws Exception{

    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte encrypted[] = cipher.doFinal(clear);

    return encrypted;
}

     @Override
      public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.encryption_test, menu);
    return true;
}

    }

该代码已成功加密资产文件夹中的字符串以及 Xml 文件。

  import java.io.BufferedReader;
 import java.io.File;
     import java.io.FileInputStream;
     import java.io.FileOutputStream;
     import java.io.FilterWriter;
     import java.io.InputStream;
     import java.io.InputStreamReader;

     import javax.crypto.Cipher;
     import javax.crypto.CipherInputStream;
     import javax.crypto.KeyGenerator;
     import javax.crypto.SecretKey;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import org.apache.commons.codec.binary.Base64;

  public class EncryptionTest1 extends Activity {
EditText output, outputDecrypt;
EditText input;
String plainData = "";
String cipherText, decryptedText;
KeyGenerator keyGen;
SecretKey secretKey;

Cipher aesCipher;
FileOutputStream fos;

byte[] byteDataToEncrypt, byteCipherText, byteDecryptedText;
byte[] xmlStream;

@Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_encryption_test1);
    input = (EditText) findViewById(R.id.text_inputText1);
    output = (EditText) findViewById(R.id.text_Result1);
    outputDecrypt = (EditText) findViewById(R.id.text_decrypt_Result1);

    Button btn_encrypt = (Button) findViewById(R.id.btn_encrpyt1);

    btn_encrypt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            try {
                plainData = input.getText().toString();
                System.out.println("input==>>" + plainData);
                byte[] fileStreams = fileOpening("SaleReport.xml");
                byte[] DataEncrypt = encrypt(fileStreams);
                String DataDecrypt = decrypt(DataEncrypt);

            System.out.println("Decrypted Text:===>>" + DataDecrypt);
                outputDecrypt.setText(DataDecrypt);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });
  }

private byte[] fileOpening(String fileName) throws Exception {
    InputStream is = getAssets().open(fileName);
    int size = is.available();
    xmlStream = new byte[size];
    is.read(xmlStream);
    System.out.println("xmlstream length==>>" + xmlStream.length);
    return xmlStream;
}

private byte[] encrypt(byte[] xmlStream) throws Exception {

    keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    secretKey = keyGen.generateKey();
    aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
    // byteDataToEncrypt = plainData.getBytes();

    byteCipherText = aesCipher.doFinal(xmlStream);
    cipherText = new String(new Base64().encodeBase64(byteCipherText));
    output.setText(cipherText);
    System.out.println(cipherText);

    return byteCipherText;

}

public String decrypt(byte[] DataEncrypt) throws Exception {
    aesCipher.init(Cipher.DECRYPT_MODE, secretKey,
    aesCipher.getParameters());
    byteDecryptedText = aesCipher.doFinal(DataEncrypt);
    decryptedText = new String(byteDecryptedText);
    return decryptedText;
  }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.encryption_test1, menu);
    return true;
}

   }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 中的字符串加密 的相关文章

随机推荐

  • 使用 Maven 3 时 Cobertura 代码覆盖率为 0%

    读完这篇文章后 将 Cobertura 与 Maven 3 0 2 一起使用的正确方法是什么 https stackoverflow com questions 6931360 what is the proper way to use c
  • python csv按列转换为字典

    是否可以将 csv 文件中的数据读取到字典中 使得列的第一行是键 同一列的其余行构成列表的值 例如 我有一个 csv 文件 strings numbers colors string1 1 blue string2 2 red string
  • 将字符串中的字符向左移动

    我是 Stack Overflow 的新手 有一道编程课的实验室问题一直困扰着我 该问题要求我们将字符串 s 的元素向左移动 k 次 例如 如果输入是 Hello World 和3 它将输出 lo WorldHel 对于非常大的 k 值 它
  • Haskell 中的实例声明

    我有这两个功能 primes sieve 2 where sieve p xs p sieve x x lt xs x mod p gt 0 isPrime number number 1 null x x lt takeWhile x g
  • 如何跟踪数据库连接泄漏

    我们有一个应用程序似乎存在连接泄漏 SQL Server 表示已达到最大池大小 我独自一人在我的开发机器上 显然 只需导航应用程序 我就会触发此错误 SQL Server 活动监视器显示大量正在使用我的数据库的进程 我想查找哪些文件打开连接
  • Scala repl 抛出错误

    当我打字时scala在终端上启动 repl 它会抛出此错误 scala gt init error error while loading AnnotatedElement class file usr lib jvm java 8 ora
  • Android:如何为我的应用程序播放的任何音乐文件创建淡入/淡出音效?

    我正在开发的应用程序播放音乐文件 如果计时器到期 我希望音乐淡出 我怎么做 我正在使用 MediaPlayer 播放音乐 音乐文件位于我的应用程序的原始文件夹中 这是我的 Android MediaPlayer 的整个处理程序类 查看 pl
  • 具有 MVC4 风格捆绑的 Intellisense

    到目前为止我找不到问题或解决这个问题 我确信我错过了一些简单的事情 我有一个带有一堆缩小的 CSS 的样式包 并且我正在用里面的类来装饰 HTML 元素 一切都运转良好 然而 Intellisense 和 ReSharper 都因为 CSS
  • DRF:以编程方式从 TextChoices 字段获取默认选择

    我们的网站是 Vue 前端 DRF 后端 在一个serializer validate 方法 我需要以编程方式确定哪个选项TextChoices类已被指定为模型字段的默认值 TextChoices 类 缩写示例 class PaymentM
  • Angular 2 变更检测是如何工作的?

    在 Angular 1 中 更改检测是通过对 scope 层次结构进行脏检查来进行的 我们会在模板 控制器或组件中隐式或显式创建观察者 在 Angular 2 中 我们不再有 scope 但我们确实重写了 setInterval setTi
  • VS C# 中的依赖地狱,找不到依赖项

    我创建了一个图表 C 库 我们称之为chartlibrary 它本身依赖于多个第三方 dll 文件 在另一个可执行项目中 我们称之为chartuser 我参考了chartlibrary项目 两个项目位于 Visual Studio 中的同一
  • HTML 文本框,自动突出显示文本

    我将如何制作一个包含预先存在的文本的文本框 当用户在其中单击时 其中的所有文本都会突出显示 例如 YouTube 在其视频上使用嵌入代码的文本框的方式相同 谢谢 如果我正确理解你的问题 你可以使用一些javascript 未经测试的代码
  • 为什么 std::atomic 比 volatile bool 慢很多?

    多年来我一直使用 volatile bool 来控制线程执行 并且效果很好 in my class declaration volatile bool stop In the thread function while stop do th
  • Android 在通话期间播放音频文件[重复]

    这个问题在这里已经有答案了 对于我的 Android 应用程序 我想在从应用程序接听电话后播放音频文件 应用程序将发起电话呼叫 一旦接收者接听电话 应用程序应开始播放录制的音频文件 通过在谷歌上进行大量搜索 我发现这对于未root的设备来说
  • 如何使用 cf 程序查看我的 VCAP_SERVICES 环境变量?

    当我跑步时cf env
  • Zsh 中的鱼式自我暗示?

    有没有办法做到鱼的自我暗示类型 http ridiculousfish com shell images autosuggestion png in Zsh https github com tarruda zsh autosuggesti
  • 春季启动大战

    我倾向于在开发过程中使用可运行的 JAR 但我需要 WAR 来进行部署 我已经关注了this http spring io guides gs convert jar to war 有关从 JAR 转换为 WAR Spring Boot G
  • 如何使用 Javascript 从 Chrome iOS 下载 blob 文件?

    如何使用 Javascript 从 Chrome iOS 下载 blob 文件 我正在从 iOS 下载文件 pdf excel txt png iOS 没有文件系统 这对下载来说是一个问题 我创建了一个代码 根据操作系统和导航器 如果需要
  • 检测 perl 中声明的包变量

    Given package main our f sub f sub g 1 我怎样才能确定 f 但不是 g 已宣布 即兴的 我以为 main g SCALAR 可能是未定义的 但它是一个善意标量参考值 背景 我想将一个变量导入到main
  • Android 中的字符串加密

    我正在使用代码进行加密和加密 它没有给出字符串结果 字节数组未转换为字符串 我几乎尝试了所有方法将字节数组转换为字符 但没有给出结果 public class EncryptionTest extends Activity EditText