如何在java中将数据加密为没有特殊字符的纯文本

时间:2015-05-07 04:38:35

标签: java encryption aes

我需要一种加密算法,我可以将数据加密成简单的纯文本。

目前我正在使用 AES 加密算法转换为加密字符串包含特殊字符。

如果我通过url中的查询字符串发送此字符串,我会遗漏一些字符,如#" +"。

所以我需要一个安全且只包含字母表的加密逻辑。

这是我的加密逻辑:

      public static String encrypt(String Data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encVal);
        return encryptedValue;
    }

    @SuppressWarnings("restriction")
    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

我在这里获得一个加密的字符串" TEj + TWBQExpz8 / p5SAjIhA == "

当我通过查询字符串发送

本地主机:8080 / myproject的/家庭代码= TEJ + TWBQExpz8 / p5SAjIhA ==

我在控制器中获取字符串as-
    " TEj TWBQExpz8 / p5SAjIhA == "

" +"符号丢失,这就是为什么我在解密时遇到问题。

请建议任何新算法或任何解决方案以避免特殊字符。

谢谢。

6 个答案:

答案 0 :(得分:4)

您可以使用URLEncoder

对加密部分进行编码
URLEncoder.encode("TEj+TWBQExpz8/p5SAjIhA==", "UTF-8")

使其对网址有效。

http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html

答案 1 :(得分:2)

您应该尝试Apache Commons Base64 URL safe encoder,它将生成您需要的内容。

希望它有所帮助,

何塞路易斯

答案 2 :(得分:1)

在通过URL发送加密值之前,您必须使用createOnEnter: function(e) { var self = this; this.input = this.$("#new-todo"); if (e.keyCode != 13) return; this.todos.create({ content: this.input.val(), order: this.todos.nextOrder(), done: false, user: Parse.User.current(), ACL: new Parse.ACL("Administrator") //Parse.User.current()) }); 对其进行编码。

在解密方面,您必须先使用Add-Type -TypeDefinition @" using System; using System.Diagnostics; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STARTUPINFO { public uint cb; public string lpReserved; public string lpDesktop; public string lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public STARTF dwFlags; public ShowWindow wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int length; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } [Flags] public enum CreationFlags : int { NONE = 0, DEBUG_PROCESS = 0x00000001, DEBUG_ONLY_THIS_PROCESS = 0x00000002, CREATE_SUSPENDED = 0x00000004, DETACHED_PROCESS = 0x00000008, CREATE_NEW_CONSOLE = 0x00000010, CREATE_NEW_PROCESS_GROUP = 0x00000200, CREATE_UNICODE_ENVIRONMENT = 0x00000400, CREATE_SEPARATE_WOW_VDM = 0x00000800, CREATE_SHARED_WOW_VDM = 0x00001000, CREATE_PROTECTED_PROCESS = 0x00040000, EXTENDED_STARTUPINFO_PRESENT = 0x00080000, CREATE_BREAKAWAY_FROM_JOB = 0x01000000, CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, CREATE_DEFAULT_ERROR_MODE = 0x04000000, CREATE_NO_WINDOW = 0x08000000, } [Flags] public enum STARTF : uint { STARTF_USESHOWWINDOW = 0x00000001, STARTF_USESIZE = 0x00000002, STARTF_USEPOSITION = 0x00000004, STARTF_USECOUNTCHARS = 0x00000008, STARTF_USEFILLATTRIBUTE = 0x00000010, STARTF_RUNFULLSCREEN = 0x00000020, // ignored for non-x86 platforms STARTF_FORCEONFEEDBACK = 0x00000040, STARTF_FORCEOFFFEEDBACK = 0x00000080, STARTF_USESTDHANDLES = 0x00000100, } public enum ShowWindow : short { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_FORCEMINIMIZE = 11, SW_MAX = 11 } public static class wtsapi32 { [DllImport("wtsapi32.dll", SetLastError = true)] public static extern bool WTSQueryUserToken(Int32 sessionId, out IntPtr Token); } public static class advapi32 { [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern bool CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, CreationFlags creationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); } "@ $sessionID = 2 $token = [IntPtr]::Zero $ret = [wtsapi32]::WTSQueryUserToken($sessionID, [ref] $token) $si = New-Object STARTUPINFO $pi = New-Object PROCESS_INFORMATION $si.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($si) $si.wShowWindow = [ShowWindow]::SW_SHOW $pSec = New-Object SECURITY_ATTRIBUTES $tSec = New-Object SECURITY_ATTRIBUTES $pSec.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($pSec) $tSec.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($tSec) $dwCreationFlags = [CreationFlags]::NORMAL_PRIORITY_CLASS -bor [CreationFlags]::CREATE_NEW_CONSOLE [advapi32]::CreateProcessAsUser($token, "c:\windows\notepad.exe", $null, [ref] $pSec, [ref] $tSec, $false, $dwCreationFlags, [IntPtr]::Zero, "c:", [ref] $si, [ref] $pi) 来解码收到的数据。

您可以在代码中执行以下操作:

URLEncoder

答案 3 :(得分:0)

仅使用URLEncode无需更改代码。

String encodedStr = URLEncoder.encode(encrypt("XYZ"), "UTF-8");

并且不需要使用URLDecode来解码url,因为您可以使用normal decrypt(encodedStr);

答案 4 :(得分:0)

在通过URL发送加密值之前,必须在C#应用程序中使用此值对加密值进行编码。 解密方面,您必须首先使用UrlDecode来解码QueryString数据。

 Server.UrlEncode("");
 Server.UrlDecode("");

答案 5 :(得分:0)

我在基于Spring的应用程序中遇到了同样的问题,并通过Base64编码/解码过程解决了该问题。

编码:

String encryptedString = encrypt(stringData);
byte[] encoded = Base64.getEncoder().encode(encryptedString.getBytes(StandardCharsets.UTF_8));
String base64Encoded = new String(encoded);

解码:

byte[] decoded = Base64.getDecoder().decode(base64Encoded.getBytes(StandardCharsets.UTF_8));
String encryptedString = new String(decoded);

比起您可以在解密方法上成功解密“ encryptedString”值而言。

String decryptedString = decrypt(encryptedString);

希望对您有帮助。