如何使用Java中的密码加密和解密String(Pc不是移动平台)? [英] How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

查看:130
本文介绍了如何使用Java中的密码加密和解密String(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中的String

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

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?

有没有其他的方法?

推荐答案

软件包com.example;

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中的密码加密和解密String(Pc不是移动平台)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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