This question already has answers here:
Java 256-bit AES Password-Based Encryption

(9个答案)


在11个月前关闭。




我想加密一个字符串,然后将其放在文件中。我也想在需要时解密它。我不需要非常强大的安全性。我只是想让别人更难获得我的数据。

我尝试了几种方法。这些是。

Md5加密:

How to hash a string in Android?
public static final String md5(final String toEncrypt) {
        try {
            final MessageDigest digest = MessageDigest.getInstance("md5");
            digest.update(toEncrypt.getBytes());
            final byte[] bytes = digest.digest();
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(String.format("%02X", bytes[i]));
            }
            return sb.toString().toLowerCase();
        } catch (Exception exc) {
            return ""; // Impossibru!
        }
    }

我尝试了此功能,并且可以加密字符串,但是无法从中解密数据。因此,这不是解决方案。

DES加密:

Encrypt and decrypt a String in java

密码是自动生成的。密码总是总是一样吗?那我的安全在哪里。所以这也不是我的解决方案。

AES加密:

How do I encrypt/decrypt a string with another string as a password?

我也从此链接尝试了Aes。这里的 key 也是自动生成的吗?

还有其他办法吗?

最佳答案

package com.example;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{
    public void run()
    {
        try
        {
            String text = "Hello World";
            String key = "Bar12345Bar12345"; // 128 bit key
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            // encrypt the text
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(text.getBytes());
            System.err.println(new String(encrypted));
            // decrypt the text
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            String decrypted = new String(cipher.doFinal(encrypted));
            System.err.println(decrypted);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        StrongAES app = new StrongAES();
        app.run();
    }
}

10-07 19:20
查看更多