It is possible to know if a string is encoded in b

2019-04-14 11:47发布

问题:

Simple as that.

I'm making an app where the user has to scan a QR code (which basically is a base64 encoded string), is there any way to verify that the string is encoded in base64 before decode and follow the flow of the application?

My code would be responsible for that is:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {

    if metadataObjects == nil || metadataObjects.count == 0 {
        qrCodeFrameView?.frame = CGRectZero
        return
    }

    let metadataObj = metadataObjects[0] as AVMetadataMachineReadableCodeObject

    if metadataObj.type == AVMetadataObjectTypeQRCode {
        let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj as AVMetadataMachineReadableCodeObject) as AVMetadataMachineReadableCodeObject
        qrCodeFrameView?.frame = barCodeObject.bounds

        if metadataObj.stringValue != nil /* Verify that string is base 64 before continue */ {
            let decodedData = NSData(base64EncodedString: metadataObj.stringValue, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
            let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
            println(decodedString)
        }

        /* More code */

    }
}

回答1:

There is no need to check in advance if the string contains valid Base-64. You just have to check the return value, which is nil when the input is not recognized as valid Base-64:

if let decodedData = NSData(base64EncodedString: someString, options: nil) {
    // ...
} else {
    println("Not Base64")
}

Update for Swift 4:

if let decodedData = Data(base64Encoded: someString) {
    // ...
} else {
    print("Not Base64")
}


回答2:

You can use the regular expression to check a string match base64 encoding or not, like this:

^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$

In base64 encoding, the character set is [A-Z,a-z,0-9,and + /], if rest length is less than 4, fill of '=' character.

^([A-Za-z0-9+/]{4})* means the String start with 0 time or more base64 group.

([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==) means the String must end of 3 forms in [A-Za-z0-9+/]{4} or [A-Za-z0-9+/]{3}= or [A-Za-z0-9+/]{2}==

Basic Rule is:

  • Check that the length is a multiple of 4 characters
  • Check that every character is in the set A-Z, a-z, 0-9, +, / except for padding at the end which is 0, 1 or 2 '=' characters


回答3:

Please Use For Base64 Validation

OtherWise Add The Pod in The Project pod 'SwiftValidators'

Example

if Validators.isBase64()("mnbzcxmnbnzzxmnb==")
{
print("Validate Yes")
}
else
{
print("Not Validate")
}