flash.net

# SecureSocket - AS3

Package | flash.net
Class | public class SecureSocket
Inheritance | SecureSocket Socket EventDispatcher Object

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

The SecureSocket class enables code to make socket connections using the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.

AIR profile support: This feature is supported on all desktop operating systems, but is not supported on all AIR for TV devices. On mobile devices, it is supported on Android and also supported on iOS starting from AIR 20. You can test for support at run time using the `SecureSocket.isSupported` property. See AIR Profile Support for more information regarding API support across multiple profiles.

The SSL/TLS protocols provide a mechanism to handle both aspects of a secure socket connection:

1. Encryption of data communication over the socket
2. Authentication of the host's identity via its certificate

The supported encryption protocols are SSL 3.1 and higher, and TLS 1.0 and higher. (TLS is the successor protocol for SSL. TLS 1.0 equals SSL 3.1, TLS 1.1 equals SSL 3.2, and so on.) SSL versions 3.0 or lower are not supported.

Validation of the server certificate is performed using the trust store and certificate validation support of the client platform. In addition you can add your own certificates programmatically with the `addBinaryChainBuildingCertificate()` method.This API isn't supported on iOS currently. Using this API on iOS would throw an exception - "ArgumentError: Error #2004"

The SecureSocket class only connects to servers with valid, trusted certificates. You cannot choose to connect to a server in spite of a problem with its certificate. For example, there is no way to connect to a server with an expired certificate. The same is true for a certificate that doesn't chain to a trusted anchor certificate. The connection will not be made, even though the certificate would be valid otherwise.

The SecureSocket class is useful for performing encrypted communication to a trusted server. In other respects, a SecureSocket object behaves like a regular Socket object.

To use the SecureSocket class, create a SecureSocket object (`new SecureSocket()`). Next, set up your listeners, and then run `SecureSocket.connect(host, port)`. When you successfully connect to the server, the socket dispatches a `connect` event. A successful connection is one in which the server's security protocols are supported and its certificate is valid and trusted. If the certificate cannot be validated, the Socket dispatches an `IOError` event.

Important: The Online Certificate Status Protocol (OCSP) is not supported by all operating systems. Users can also disable OCSP checking on individual computers. If OCSP is not supported or is disabled and a certificate does not contain the information necessary to check revocation using a Certificate Revocation List (CRL), then certificate revocation is not checked. The certificate is accepted if otherwise valid. This scenario could allow a server to use a revoked certificate.

View the examples

More examples

Binary client sockets

Related API Elements

Socket class

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| Property | Defined By
--- | --- | ---
|  | bytesAvailable : uint [read-only] The number of bytes of data available for reading in the input buffer. | Socket
|  | bytesPending : uint [read-only] Indicates the number of bytes remaining in the write buffer. | Socket
|  | connected : Boolean [read-only] Indicates whether this Socket object is currently connected. | Socket
|  | constructor : Object A reference to the class object or constructor function for a given object instance. | Object
|  | endian : String Indicates the byte order for the data. | Socket
|  | isSupported : Boolean [static] [read-only] Indicates whether secure sockets are supported on the current system. | SecureSocket
|  | localAddress : String [read-only] The IP address this socket is bound to on the local machine. | Socket
|  | localPort : int [read-only] The port this socket is bound to on the local machine. | Socket
|  | objectEncoding : uint Controls the version of AMF used when writing or reading an object. | Socket
|  | remoteAddress : String [read-only] The IP address of the remote machine to which this socket is connected. | Socket
|  | remotePort : int [read-only] The port on the remote machine to which this socket is connected. | Socket
|  | serverCertificate : X509Certificate [read-only] Holds the X.509 certificate obtained from the server after a secure SSL/TLS connection is established. | SecureSocket
|  | serverCertificateStatus : String [read-only] Returns the status of the server's certificate. | SecureSocket
|  | timeout : uint Indicates the number of milliseconds to wait for a connection. | Socket

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | SecureSocket() Creates a new SecureSocket object. | SecureSocket
|  | addBinaryChainBuildingCertificate(certificate:ByteArray, trusted:Boolean):void Adds an X.509 certificate to the local certificate chain that your system uses for validating the server certificate. | SecureSocket
|  | addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. | EventDispatcher
|  | close():void Closes the socket. | Socket
|  | connect(host:String, port:int):void [override] Connects the socket to the specified host and port using SSL or TLS. | SecureSocket
|  | dispatchEvent(event:Event):Boolean Dispatches an event into the event flow. | EventDispatcher
|  | flush():void Flushes any accumulated data in the socket's output buffer. | Socket
|  | hasEventListener(type:String):Boolean Checks whether the EventDispatcher object has any listeners registered for a specific type of event. | EventDispatcher
|  | hasOwnProperty(name:String):Boolean Indicates whether an object has a specified property defined. | Object
|  | isPrototypeOf(theClass:Object):Boolean Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter. | Object
|  | propertyIsEnumerable(name:String):Boolean Indicates whether the specified property exists and is enumerable. | Object
|  | readBoolean():Boolean Reads a Boolean value from the socket. | Socket
|  | readByte():int Reads a signed byte from the socket. | Socket
|  | readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void Reads the number of data bytes specified by the length parameter from the socket. | Socket
|  | readDouble():Number Reads an IEEE 754 double-precision floating-point number from the socket. | Socket
|  | readFloat():Number Reads an IEEE 754 single-precision floating-point number from the socket. | Socket
|  | readInt():int Reads a signed 32-bit integer from the socket. | Socket
|  | readMultiByte(length:uint, charSet:String):String Reads a multibyte string from the byte stream, using the specified character set. | Socket
|  | readObject():* Reads an object from the socket, encoded in AMF serialized format. | Socket
|  | readShort():int Reads a signed 16-bit integer from the socket. | Socket
|  | readUnsignedByte():uint Reads an unsigned byte from the socket. | Socket
|  | readUnsignedInt():uint Reads an unsigned 32-bit integer from the socket. | Socket
|  | readUnsignedShort():uint Reads an unsigned 16-bit integer from the socket. | Socket
|  | readUTF():String Reads a UTF-8 string from the socket. | Socket
|  | readUTFBytes(length:uint):String Reads the number of UTF-8 data bytes specified by the length parameter from the socket, and returns a string. | Socket
|  | removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void Removes a listener from the EventDispatcher object. | EventDispatcher
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | toLocaleString():String Returns the string representation of this object, formatted according to locale-specific conventions. | Object
|  | toString():String Returns the string representation of the specified object. | Object
|  | valueOf():Object Returns the primitive value of the specified object. | Object
|  | willTrigger(type:String):Boolean Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. | EventDispatcher
|  | writeBoolean(value:Boolean):void Writes a Boolean value to the socket. | Socket
|  | writeByte(value:int):void Writes a byte to the socket. | Socket
|  | writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void Writes a sequence of bytes from the specified byte array. | Socket
|  | writeDouble(value:Number):void Writes an IEEE 754 double-precision floating-point number to the socket. | Socket
|  | writeFloat(value:Number):void Writes an IEEE 754 single-precision floating-point number to the socket. | Socket
|  | writeInt(value:int):void Writes a 32-bit signed integer to the socket. | Socket
|  | writeMultiByte(value:String, charSet:String):void Writes a multibyte string from the byte stream, using the specified character set. | Socket
|  | writeObject(object:*):void Write an object to the socket in AMF serialized format. | Socket
|  | writeShort(value:int):void Writes a 16-bit integer to the socket. | Socket
|  | writeUnsignedInt(value:uint):void Writes a 32-bit unsigned integer to the socket. | Socket
|  | writeUTF(value:String):void Writes the following data to the socket: a 16-bit unsigned integer, which indicates the length of the specified UTF-8 string in bytes, followed by the string itself. | Socket
|  | writeUTFBytes(value:String):void Writes a UTF-8 string to the socket. | Socket

Events
Click for more information on events
Hide Inherited Events
Show Inherited Events

| Event | Summary | Defined By
--- | --- | --- | ---
|  | activate | [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active. | EventDispatcher
|  | close | Dispatched when the server closes the socket connection. | SecureSocket
|  | connect | Dispatched when a network connection has been established. | SecureSocket
|  | deactivate | [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive. | EventDispatcher
|  | ioError | Dispatched when an input or output error occurs that causes a send or receive operation to fail. | SecureSocket
|  | outputProgress | Dispatched when a socket moves data from its write buffer to the networking transport layer | Socket
|  | securityError | Dispatched when a call to SecureSocket.connect() fails because of a security restriction. | SecureSocket
|  | socketData | Dispatched when a socket has received data. | SecureSocket

Property Detail

### isSupported

property

`isSupported:Boolean` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Indicates whether secure sockets are supported on the current system.

Secure sockets are not supported on all platforms. Check this property before attempting to create a SecureSocket instance.

Implementation
`public static function get isSupported():Boolean`

### serverCertificate

property

`serverCertificate:X509Certificate` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 3

Holds the X.509 certificate obtained from the server after a secure SSL/TLS connection is established. If a secure connection is not established, this property is set to `null`. Currently it is not supported on iOS, and hence it is set to `null` in case of iOS.

For more information on X.509 certificates, see RFC2459.

Implementation
`public function get serverCertificate():X509Certificate`

### serverCertificateStatus

property

`serverCertificateStatus:String` [read-only]

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Returns the status of the server's certificate.

The status is `CertificateStatus.UNKNOWN` until the socket attempts to connect to a server. After validation, the status is one of the strings enumerated by the CertificateStatus class. The connection only succeeds when the certificate is valid and trusted. Thus, after a `connect` event, the value of `serverCertificateStatus` is always `trusted`.

Note: Once the certificate has been validated or rejected, the status value is not updated until the next call to the `connect()` method. Calling `close()` does not reset the status value to "unknown".

Implementation
`public function get serverCertificateStatus():String`

Related API Elements

CertificateStatus class
Constructor Detail

### SecureSocket

()
Constructor

`public function SecureSocket()`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Creates a new SecureSocket object.

Check `SecureSocket.isSupported` before attempting to create a SecureSocket instance. If SSL 3.0 or TLS 1.0 sockets are not supported, the runtime will throw an IllegalOperationError.

Throws

| `IllegalOperationError` — When SSL Version 3.0 (and higher) or TLS Version 1.0 (and higher) is not supported.
| `SecurityError` — Local untrusted SWF files cannot communicate with the Internet. You can work around this problem by reclassifying this SWF file as local-with-networking or trusted.

Method Detail

### addBinaryChainBuildingCertificate

()
method

`public function addBinaryChainBuildingCertificate(certificate:ByteArray, trusted:Boolean):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 3

Adds an X.509 certificate to the local certificate chain that your system uses for validating the server certificate. The certificate is temporary, and lasts for the duration of the session.

Server certificate validation relies on your system's trust store for certificate chain building and validation. Use this method to programmatically add additional certification chains and trusted anchors.

On Mac OS, the System keychain is the default keychain used during the SSL/TLS handshake process. Any intermediate certificates in that keychain are included when building the certification chain.

The certificate you add with this API must be a DER-encoded X.509 certificate. If the `trusted` parameter is true, the certificate you add with this API is considered a trusted anchor.

For more information on X.509 certificates, see RFC2459.

Parameters

| `certificate:ByteArray` — A ByteArray object containing a DER-encoded X.509 digital certificate.
| `trusted:Boolean` — Set to true to designate this certificate as a trust anchor.

Throws

| `ArgumentError` — When the certificate cannot be added.

### connect

()
method

`override public function connect(host:String, port:int):void`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Connects the socket to the specified host and port using SSL or TLS.

When you call the `SecureSocket.connect()` method, the socket attempts SSL/TLS handshaking with the server. If the handshake succeeds, the socket attempts to validate the server certificate. If the certificate is valid and trusted, then the secure socket connection is established, and the socket dispatches a `connect` event. If the handshake fails or the certificate cannot be validated, the socket dispatches an `IOError` event. You can check the certificate validation result by reading the `serverCertificateStatus` property after the `IOError` event is dispatched. (When a `connect` event is dispatched, the certificate status is always `trusted`.)

If the socket was already connected, the existing connection is closed first.

Parameters

| `host:String` — The name or IP address of the host to connect to.
| `port:int` — The port number to connect to.

Events

| `connect:`Event`` — Dispatched when a network connection has been established.
| `ioError:`IOErrorEvent`` — Dispatched if a host is specified and an input/output error occurs that causes the connection to fail. This includes SSL/TLS handshake errors and failure to successfully validate the host's server certificate.
| `securityError:`SecurityErrorEvent`` — Dispatched if a call to `Socket.connect()` attempts to connect either to a server that doesn't serve a socket policy file, or to a server whose policy file doesn't grant the calling host access to the specified port. For more information on policy files, see "Website controls (policy files)" in the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: Security.

Throws

| `IOError` — When you don't specify a host and the connection fails.
| `SecurityError` — When you specify a socket port less than zero or higher than 65535.

Event Detail

### close

Event

Event Object Type: `flash.events.Event`
property Event.type = `flash.events.Event.CLOSE`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Dispatched when the server closes the socket connection.

The `close` event is dispatched only when the server closes the connection; it is not dispatched when you call the `Socket.close()` method.

The `Event.CLOSE` constant defines the value of the `type` property of a `close` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`target` | The object whose connection has been closed.

### connect

Event

Event Object Type: `flash.events.Event`
property Event.type = `flash.events.Event.CONNECT`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Dispatched when a network connection has been established.

The `Event.CONNECT` constant defines the value of the `type` property of a `connect` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`target` | The Socket or XMLSocket object that has established a network connection.

### ioError

Event

Event Object Type: `flash.events.IOErrorEvent`
property IOErrorEvent.type = `flash.events.IOErrorEvent.IO_ERROR`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Dispatched when an input or output error occurs that causes a send or receive operation to fail.

When a server certificate cannot be validated, the error event dispatched is an IOError. In this case, you can check the `serverCertificateStatus` property to determine the cause of the problem.

Defines the value of the `type` property of an `ioError` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`errorID` | A reference number associated with the specific error (AIR only).
`target` | The network object experiencing the input/output error.
`text` | Text to be displayed as an error message.

### securityError

Event

Event Object Type: `flash.events.SecurityErrorEvent`
property SecurityErrorEvent.type = `flash.events.SecurityErrorEvent.SECURITY_ERROR`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Dispatched when a call to `SecureSocket.connect()` fails because of a security restriction.

A security error event is dispatched when code running in Flash Player or in AIR outside the application security sandbox attempts to connect to a server in a different domain or to a port lower than 1024 and the server does not provide a policy file that allows the connection. Note that code running within the AIR application sandbox can connect to a server at any domain and on ports below 1024 without a policy file.

The `SecurityErrorEvent.SECURITY_ERROR` constant defines the value of the `type` property of a `securityError` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event object with an event listener.
`target` | The network object reporting the security error.
`text` | Text to be displayed as an error message.

Related API Elements

SecureSocket.connect()

### socketData

Event

Event Object Type: `flash.events.ProgressEvent`
property ProgressEvent.type = `flash.events.ProgressEvent.SOCKET_DATA`

Language Version: | ActionScript 3.0

Runtime Versions: | Flash Player 11, AIR 2

Dispatched when a socket has received data. Events of type `socketData` do not use the `ProgressEvent.bytesTotal` property.

Defines the value of the `type` property of a `socketData` event object.

This event has the following properties:

Property | Value
--- | ---
`bubbles` | `false`
`cancelable` | `false`; there is no default behavior to cancel.
`currentTarget` | The object that is actively processing the Event.
`bytesLoaded` | The number of items or bytes loaded at the time the listener processes the event.
`bytesTotal` | 0; this property is not used by `socketData` event objects.
`target` | The socket reporting progress.

Examples How to use this example
SecureSocketExample.as
The following example illustrates how to create and connect a SecureSocket object.
Copy

    package
    {
        import flash.display.Sprite;
        import flash.errors.IOError;
        import flash.events.Event;
        import flash.events.IOErrorEvent;
        import flash.net.SecureSocket;

        public class SecureSocketExample extends Sprite
        {
            private var secureSocket:SecureSocket = new SecureSocket();

            public function SecureSocketExample()
            {
                secureSocket.addEventListener( Event.CONNECT, onConnect )
                secureSocket.addEventListener( IOErrorEvent.IO_ERROR, onError );

                try
                {
                    secureSocket.connect( "208.77.188.166", 443 );
                }
                catch ( error:Error )
                {
                    trace ( error.toString() );
                }
            }

            private function onConnect( event:Event ):void
            {
                trace("Connected.");
            }

            private function onError( error:IOErrorEvent ):void
            {
                trace( error.text + ", " + secureSocket.serverCertificateStatus );
            }
        }
    }

© 2015 Adobe Systems Incorporated. All rights reserved.
Mon Apr 10 2017, 12:28 PM -07:00