字符串到Byte []并返回String

时间:2015-08-02 04:14:58

标签: java string encryption bytearray rc4-cipher

我有一个

String X = 0110100001100101011011000110110001101111530940929e959001f70dd4da5f5cc3b373165781

我首先通过X.getBytes()将String X变成byte []; 我使用这个来进行RC4加密..

public static byte[] RC4(byte[] x,byte[] keyBytes)   
{   
    byte[] e = null; 

    try   
    {   
        SecureRandom sr = new SecureRandom(keyBytes);
        KeyGenerator kg = KeyGenerator.getInstance(algorithm);
        kg.init(sr);
        SecretKey sk = kg.generateKey();  
        Cipher enCipher = Cipher.getInstance("RC4");   
        enCipher.init(Cipher.ENCRYPT_MODE,sk);   
        e = enCipher.doFinal(plaintext);              
    }   
    catch(Exception ex)   
    {   
        ex.printStackTrace();   
    }   
    return e;   
} 

编辑** 我使用cipher = encrpyted.toString();加密后 这会返回cipher = [B@a1c582

的值

之后我尝试使用RC4运行解密,并尝试使用toString函数来获取上面列出的String X的原始值,但无济于事。

我做了什么.. 编辑**

//the reason i send using string is due to me having a client server architecture restriction on buffered writer, and this is the receiving side

            message = stdIn.readLine();
            System.out.println("Message received : " + message);

            byte [] kc = key.getBytes();
            byte [] decrypt = message.getBytes();
            byte [] decryptC = EncryptionScheme.decrypt(decrypt, kc);
            X = new String(decryptC);
            System.out.println("String X = " + X);

Message received : [B@a1c582

String X = ����,��

有什么方法可以解决这个问题吗?我希望找回String X = 0110100001100101011011000110110001101111530940929e959001f70dd4da5f5cc3b373165781

的字符串
decryption algorithm

    public static byte[] decrypt(byte[] ciphertext,byte[] keyBytes)   
    {   
        byte de[] = null;   
        try   
        {   
            SecureRandom sr = new SecureRandom(keyBytes);
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            kg.init(sr);
            SecretKey sk = kg.generateKey();    
            Cipher deCipher = Cipher.getInstance("RC4");   
            deCipher.init(Cipher.DECRYPT_MODE,sk);   
            de = deCipher.doFinal(ciphertext);   
        }   
        catch(Exception e)   
        {   
            e.printStackTrace();   
        }    
        return de;   

    }  

2 个答案:

答案 0 :(得分:0)

如果您找不到更好的解决方案,可以执行以下操作

    StringBuilder s = new StringBuilder();
    for(byte b : arr) {
        s.append(Integer.toBinaryString(0x100 | 0xFF & b).substring(1, 9));
    }

答案 1 :(得分:0)

  

加密后我使用cipher = encrpyted.toString()

这是无效的。所有这些都是调用Object.toString()的结果,byte[]是对象类([B,编码为System.identityHashCode())及其String的组合。如果这是你通过网络发送的,这是我可以从你的帖子中得出的唯一结论,你不可能正确地解密它,因为它首先不包含密文。

由于@RequestMapping(value = "/ipnHandler.html") public void handleIpn (HttpServletRequest request) throws IpnException { logger.info("inside ipn"); IpnInfo ipnInfo = new IpnInfo(); Enumeration reqParamNames = request.getParameterNames(); StringBuilder cmd1 = new StringBuilder(); String pName; String pValue; cmd1.append("cmd=_notify-validate"); while (reqParamNames.hasMoreElements()) { pName = (String) reqParamNames.nextElement(); pValue = request.getParameter(pName); try{ cmd1.append("&").append(pName).append("=").append(pValue); } catch(Exception e){ e.printStackTrace(); } } try { URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr"); HttpsURLConnection con = (HttpsURLConnection) u.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Host", "www.sandbox.paypal.com/cgi-bin/webscr"); con.setRequestProperty("Content-length", String.valueOf(cmd1.length())); con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)"); con.setDoOutput(true); con.setDoInput(true); DataOutputStream output = new DataOutputStream(con.getOutputStream()); output.writeBytes(cmd1.toString()); output.flush(); output.close(); //4. Read response from Paypal BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String res = in.readLine(); in.close(); //5. Capture Paypal IPN information ipnInfo.setLogTime(System.currentTimeMillis()); ipnInfo.setItemName(request.getParameter("item_name")); ipnInfo.setItemNumber(request.getParameter("item_number")); ipnInfo.setPaymentStatus(request.getParameter("payment_status")); ipnInfo.setPaymentAmount(request.getParameter("mc_gross")); ipnInfo.setPaymentCurrency(request.getParameter("mc_currency")); ipnInfo.setTxnId(request.getParameter("txn_id")); ipnInfo.setReceiverEmail(request.getParameter("receiver_email")); ipnInfo.setPayerEmail(request.getParameter("payer_email")); ipnInfo.setResponse(res); // ipnInfo.setRequestParams(reqParamNames); //6. Validate captured Paypal IPN Information if (res.equals("VERIFIED")) { //6.1. Check that paymentStatus=Completed if(ipnInfo.getPaymentStatus() == null || !ipnInfo.getPaymentStatus().equalsIgnoreCase("COMPLETED")) ipnInfo.setError("payment_status IS NOT COMPLETED {" + ipnInfo.getPaymentStatus() + "}"); //6.2. Check that txnId has not been previously processed IpnInfo oldIpnInfo = this.getIpnInfoService().getIpnInfo(ipnInfo.getTxnId()); if(oldIpnInfo != null) ipnInfo.setError("txn_id is already processed {old ipn_info " + oldIpnInfo); //6.3. Check that receiverEmail matches with configured {@link IpnConfig#receiverEmail} if(!ipnInfo.getReceiverEmail().equalsIgnoreCase(this.getIpnConfig().getReceiverEmail())) ipnInfo.setError("receiver_email " + ipnInfo.getReceiverEmail() + " does not match with configured ipn email " + this.getIpnConfig().getReceiverEmail()); //6.4. Check that paymentAmount matches with configured {@link IpnConfig#paymentAmount} if(Double.parseDouble(ipnInfo.getPaymentAmount()) != Double.parseDouble(this.getIpnConfig().getPaymentAmount())) ipnInfo.setError("payment amount mc_gross " + ipnInfo.getPaymentAmount() + " does not match with configured ipn amount " + this.getIpnConfig().getPaymentAmount()); //6.5. Check that paymentCurrency matches with configured {@link IpnConfig#paymentCurrency} if(!ipnInfo.getPaymentCurrency().equalsIgnoreCase(this.getIpnConfig().getPaymentCurrency())) ipnInfo.setError("payment currency mc_currency " + ipnInfo.getPaymentCurrency() + " does not match with configured ipn currency " + this.getIpnConfig().getPaymentCurrency()); } else ipnInfo.setError("Inavlid response {" + res + "} expecting {VERIFIED}"); logger.info("ipnInfo = " + ipnInfo); this.getIpnInfoService().log(ipnInfo); //7. In case of any failed validation checks, throw {@link IpnException} if(ipnInfo.getError() != null) throw new IpnException(ipnInfo.getError()); } catch(Exception e) { if(e instanceof IpnException) throw (IpnException) e; logger.log(Level.FATAL, e.toString(), e); throw new IpnException(e.toString()); } //8. If all is well, return {@link IpnInfo} to the caller for further business logic execution paymentController.processSuccessfulPayment(ipnInfo); } 不是二进制数据的容器,您必须发送密文的base-64或base-16或base-36编码,在接收器处对其进行解码,然后对其进行解密。