如何使用我的密码在 Java(PC 而非移动平台)中加密和解密字符串? [英] How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

查看:13
本文介绍了如何使用我的密码在 Java(PC 而非移动平台)中加密和解密字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加密一个字符串,然后把它放在一个文件中.也想在我想要的时候解密它.我不需要很强的安全性.我只是想让其他人更难获取我的数据.

I want to encrypt a string and then put it on a file. Also want to decrypt it when I want. I don’t need very strong security. I just want to make it harder to get my data others.

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

I tried several ways. Here are these.

Md5 加密:

如何在 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!
        }
    }

我尝试了这个功能并且能够加密一个字符串,但我无法从中解密数据.所以这不是解决方案.

I tried this function and able to encrypt a string but I can’t decrypt data from it. So it is not the solution.

DES 加密:

在java中加密和解密字符串

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

Here passphrase is Auto generated. Is always passphrase will same on all time? Then where is my security. So it is not my solution too.

AES 加密:

我该怎么做用另一个字符串作为密码加密/解密一个字符串?

我也从这个链接尝试了 Aes.这里的密钥也是自动生成的?

I also tried Aes from this link. Here key is also auto generated?

还有什么办法吗?

推荐答案

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();
    }
}

这篇关于如何使用我的密码在 Java(PC 而非移动平台)中加密和解密字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆