是否会破坏字符串

是否会破坏字符串

本文介绍了使用Stream_StringToBinary进行Base64编码会插入换行符,是否会破坏字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我疯了,但是看起来好像著名的代码在VB中运行Base64会在第73个位置插入换行符(ascii 10),这随后使编码后的字符串对于基本身份验证无效-或其他与此无关的东西问题.

Maybe I'm crazy, but it looks like the famous code to run Base64 in VB inserts a newline character (ascii 10) at the 73rd position, which subsequently makes the encoded string invalid for Basic authentication - or anything else for that matter.

原始代码:

Function Stream_StringToBinary(Text)
  Const adTypeText = 2
  Const adTypeBinary = 1

  'Create Stream object
  Dim BinaryStream 'As New Stream
  Set BinaryStream = CreateObject("ADODB.Stream")

  'Specify stream type - we want To save text/string data.
  BinaryStream.Type = adTypeText

  'Specify charset For the source text (unicode) data.
  BinaryStream.CharSet = "us-ascii"

  'Open the stream And write text/string data To the object
  BinaryStream.Open
  BinaryStream.WriteText Text

  'Change stream type To binary
  BinaryStream.Position = 0
  BinaryStream.Type = adTypeBinary

  'Ignore first two bytes - sign of
  BinaryStream.Position = 0

  'Open the stream And get binary data from the object
  Stream_StringToBinary = BinaryStream.Read

  Set BinaryStream = Nothing
End Function


Function Base64Encode(sText)
    Dim oXML, oNode

    Set oXML = CreateObject("Msxml2.DOMDocument.3.0")
    Set oNode = oXML.CreateElement("base64")
    oNode.dataType = "bin.base64"
    oNode.nodeTypedValue =Stream_StringToBinary(sText)
    Base64Encode = oNode.text
    Set oNode = Nothing
    Set oXML = Nothing
End Function

'------------------- and here goes the encoding -----------------------
  strEnc = Base64Encode( "AVERYLONGUSERNAMEHELLOTHE123:AVERYLONGPASSWORDWHYAREYOUSOLONGREALLYANNOY123")
'----------------------------------------------------------------------

结果:

QVZFUllMT05HVVNFUk5BTUVIRUxMT1RIRTEyMzpBVkVSWUxPTkdQQVNTV09SRFdIWUFSRVlP
VVNPTE9OR1JFQUxMWUFOTk9ZMTIz

类似的情况发生在非常长的UID/PWD对上.

Looks like this occurs on very long UID/PWD pairs.

有人遇到过吗?

推荐答案

这是因为Base64编码如何处理长字符串.

This is because of how the Base64 encoding deals with long strings.

因为要在编码后添加vbLf (Chr(10)),这意味着您可以安全地使用它将其删除

Because it is adding the vbLf (Chr(10)) after the encode should mean you are safe to just remove it using

strEnc = Replace(strEnc, vbLf, "")

某些语言具有不包装"参数,可以传递该参数以停止在第76个字符之后添加换行符,但是我不知道Microsoft XMLDOM实现中的一种,请在此处注明 Base64 —我们真的想要/需要每76个字符换行吗?看起来好像是在建议,但没有证据证明它曾经实施过.

Some languages have a "no wrapping" argument that can be passed to stop the Linefeed being added after the 76th character but I don't know of one in the Microsoft XMLDOM implementation, noted here Base64 -- do we really want/need line breaks every 76 characters? it looks as though it was suggested but there is no evidence it was ever implemented.

这篇关于使用Stream_StringToBinary进行Base64编码会插入换行符,是否会破坏字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 09:37