/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.media; import java.lang.ref.WeakReference; import java.util.UUID; import java.util.HashMap; import java.util.List; import android.annotation.SystemApi; import android.os.Binder; import android.os.Debug; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Parcel; import android.util.Log; /** * MediaDrm can be used to obtain keys for decrypting protected media streams, in * conjunction with {@link android.media.MediaCrypto}. The MediaDrm APIs * are designed to support the ISO/IEC 23001-7: Common Encryption standard, but * may also be used to implement other encryption schemes. *
* Encrypted content is prepared using an encryption server and stored in a content * library. The encrypted content is streamed or downloaded from the content library to * client devices via content servers. Licenses to view the content are obtained from * a License Server. *
*
** Keys are requested from the license server using a key request. The key * response is delivered to the client app, which provides the response to the * MediaDrm API. *
* A Provisioning server may be required to distribute device-unique credentials to * the devices. *
* Enforcing requirements related to the number of devices that may play content * simultaneously can be performed either through key renewal or using the secure * stop methods. *
* The following sequence diagram shows the interactions between the objects * involved while playing back encrypted content: *
*
** The app first constructs {@link android.media.MediaExtractor} and * {@link android.media.MediaCodec} objects. It accesses the DRM-scheme-identifying UUID, * typically from metadata in the content, and uses this UUID to construct an instance * of a MediaDrm object that is able to support the DRM scheme required by the content. * Crypto schemes are assigned 16 byte UUIDs. The method {@link #isCryptoSchemeSupported} * can be used to query if a given scheme is supported on the device. *
* The app calls {@link #openSession} to generate a sessionId that will uniquely identify * the session in subsequent interactions. The app next uses the MediaDrm object to * obtain a key request message and send it to the license server, then provide * the server's response to the MediaDrm object. *
* Once the app has a sessionId, it can construct a MediaCrypto object from the UUID and * sessionId. The MediaCrypto object is registered with the MediaCodec in the * {@link MediaCodec.#configure} method to enable the codec to decrypt content. *
* When the app has constructed {@link android.media.MediaExtractor}, * {@link android.media.MediaCodec} and {@link android.media.MediaCrypto} objects, * it proceeds to pull samples from the extractor and queue them into the decoder. For * encrypted content, the samples returned from the extractor remain encrypted, they * are only decrypted when the samples are delivered to the decoder. *
Applications should register for informational events in order
* to be informed of key state updates during playback or streaming.
* Registration for these events is done via a call to
* {@link #setOnEventListener}. In order to receive the respective
* callback associated with this listener, applications are required to create
* MediaDrm objects on a thread with its own Looper running (main UI
* thread by default has a Looper running).
*/
public final class MediaDrm {
private final static String TAG = "MediaDrm";
private static final String PERMISSION = android.Manifest.permission.ACCESS_DRM_CERTIFICATES;
private EventHandler mEventHandler;
private OnEventListener mOnEventListener;
private long mNativeContext;
/**
* Specify no certificate type
*
* @hide - not part of the public API at this time
*/
public static final int CERTIFICATE_TYPE_NONE = 0;
/**
* Specify X.509 certificate type
*
* @hide - not part of the public API at this time
*/
public static final int CERTIFICATE_TYPE_X509 = 1;
/**
* Query if the given scheme identified by its UUID is supported on
* this device.
* @param uuid The UUID of the crypto scheme.
*/
public static final boolean isCryptoSchemeSupported(UUID uuid) {
return isCryptoSchemeSupportedNative(getByteArrayFromUUID(uuid), null);
}
/**
* Query if the given scheme identified by its UUID is supported on
* this device, and whether the drm plugin is able to handle the
* media container format specified by mimeType.
* @param uuid The UUID of the crypto scheme.
* @param mimeType The MIME type of the media container, e.g. "video/mp4"
* or "video/webm"
*/
public static final boolean isCryptoSchemeSupported(UUID uuid, String mimeType) {
return isCryptoSchemeSupportedNative(getByteArrayFromUUID(uuid), mimeType);
}
private static final byte[] getByteArrayFromUUID(UUID uuid) {
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] uuidBytes = new byte[16];
for (int i = 0; i < 8; ++i) {
uuidBytes[i] = (byte)(msb >>> (8 * (7 - i)));
uuidBytes[8 + i] = (byte)(lsb >>> (8 * (7 - i)));
}
return uuidBytes;
}
private static final native boolean isCryptoSchemeSupportedNative(byte[] uuid,
String mimeType);
/**
* Instantiate a MediaDrm object
*
* @param uuid The UUID of the crypto scheme.
*
* @throws UnsupportedSchemeException if the device does not support the
* specified scheme UUID
*/
public MediaDrm(UUID uuid) throws UnsupportedSchemeException {
Looper looper;
if ((looper = Looper.myLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else if ((looper = Looper.getMainLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else {
mEventHandler = null;
}
/* Native setup requires a weak reference to our object.
* It's easier to create it here than in C++.
*/
native_setup(new WeakReference
* getKeyRequest() is used to obtain an opaque key request byte array that is
* delivered to the license server. The opaque key request byte array is returned
* in KeyRequest.data. The recommended URL to deliver the key request to is
* returned in KeyRequest.defaultUrl.
*
* After the app has received the key request response from the server,
* it should deliver to the response to the DRM engine plugin using the method
* {@link #provideKeyResponse}.
*
* @param scope may be a sessionId or a keySetId, depending on the specified keyType.
* When the keyType is KEY_TYPE_STREAMING or KEY_TYPE_OFFLINE,
* scope should be set to the sessionId the keys will be provided to. When the keyType
* is KEY_TYPE_RELEASE, scope should be set to the keySetId of the keys
* being released. Releasing keys from a device invalidates them for all sessions.
* @param init container-specific data, its meaning is interpreted based on the
* mime type provided in the mimeType parameter. It could contain, for example,
* the content ID, key ID or other data obtained from the content metadata that is
* required in generating the key request. init may be null when keyType is
* KEY_TYPE_RELEASE.
* @param mimeType identifies the mime type of the content
* @param keyType specifes the type of the request. The request may be to acquire
* keys for streaming or offline content, or to release previously acquired
* keys, which are identified by a keySetId.
* @param optionalParameters are included in the key request message to
* allow a client application to provide additional message parameters to the server.
*
* @throws NotProvisionedException if reprovisioning is needed, due to a
* problem with the certifcate
*/
public native KeyRequest getKeyRequest(byte[] scope, byte[] init,
String mimeType, int keyType, HashMap
* Information from the server related to the current playback session is written
* to persistent storage on the device when each MediaCrypto object is created.
*
* In the normal case, playback will be completed, the session destroyed and the
* Secure Stops will be queried. The app queries secure stops and forwards the
* secure stop message to the server which verifies the signature and notifies the
* server side database that the session destruction has been confirmed. The persisted
* record on the client is only removed after positive confirmation that the server
* received the message using releaseSecureStops().
*/
public native List
* Standard fields names are:
* {@link #PROPERTY_VENDOR}, {@link #PROPERTY_VERSION},
* {@link #PROPERTY_DESCRIPTION}, {@link #PROPERTY_ALGORITHMS}
*/
public native String getPropertyString(String propertyName);
/**
* Byte array property name: the device unique identifier is established during
* device provisioning and provides a means of uniquely identifying each device.
*/
public static final String PROPERTY_DEVICE_UNIQUE_ID = "deviceUniqueId";
/**
* Read a DRM engine plugin byte array property value, given the property name string.
*
* Standard fields names are {@link #PROPERTY_DEVICE_UNIQUE_ID}
*/
public native byte[] getPropertyByteArray(String propertyName);
/**
* Set a DRM engine plugin String property value.
*/
public native void setPropertyString(String propertyName, String value);
/**
* Set a DRM engine plugin byte array property value.
*/
public native void setPropertyByteArray(String propertyName, byte[] value);
private static final native void setCipherAlgorithmNative(MediaDrm drm, byte[] sessionId,
String algorithm);
private static final native void setMacAlgorithmNative(MediaDrm drm, byte[] sessionId,
String algorithm);
private static final native byte[] encryptNative(MediaDrm drm, byte[] sessionId,
byte[] keyId, byte[] input, byte[] iv);
private static final native byte[] decryptNative(MediaDrm drm, byte[] sessionId,
byte[] keyId, byte[] input, byte[] iv);
private static final native byte[] signNative(MediaDrm drm, byte[] sessionId,
byte[] keyId, byte[] message);
private static final native boolean verifyNative(MediaDrm drm, byte[] sessionId,
byte[] keyId, byte[] message, byte[] signature);
/**
* In addition to supporting decryption of DASH Common Encrypted Media, the
* MediaDrm APIs provide the ability to securely deliver session keys from
* an operator's session key server to a client device, based on the factory-installed
* root of trust, and then perform encrypt, decrypt, sign and verify operations
* with the session key on arbitrary user data.
*
* The CryptoSession class implements generic encrypt/decrypt/sign/verify methods
* based on the established session keys. These keys are exchanged using the
* getKeyRequest/provideKeyResponse methods.
*
* Applications of this capability could include securing various types of
* purchased or private content, such as applications, books and other media,
* photos or media delivery protocols.
*
* Operators can create session key servers that are functionally similar to a
* license key server, except that instead of receiving license key requests and
* providing encrypted content keys which are used specifically to decrypt A/V media
* content, the session key server receives session key requests and provides
* encrypted session keys which can be used for general purpose crypto operations.
*
* A CryptoSession is obtained using {@link #getCryptoSession}
*/
public final class CryptoSession {
private MediaDrm mDrm;
private byte[] mSessionId;
CryptoSession(MediaDrm drm, byte[] sessionId,
String cipherAlgorithm, String macAlgorithm)
{
mSessionId = sessionId;
mDrm = drm;
setCipherAlgorithmNative(drm, sessionId, cipherAlgorithm);
setMacAlgorithmNative(drm, sessionId, macAlgorithm);
}
/**
* Encrypt data using the CryptoSession's cipher algorithm
*
* @param keyid specifies which key to use
* @param input the data to encrypt
* @param iv the initialization vector to use for the cipher
*/
public byte[] encrypt(byte[] keyid, byte[] input, byte[] iv) {
return encryptNative(mDrm, mSessionId, keyid, input, iv);
}
/**
* Decrypt data using the CryptoSessions's cipher algorithm
*
* @param keyid specifies which key to use
* @param input the data to encrypt
* @param iv the initialization vector to use for the cipher
*/
public byte[] decrypt(byte[] keyid, byte[] input, byte[] iv) {
return decryptNative(mDrm, mSessionId, keyid, input, iv);
}
/**
* Sign data using the CryptoSessions's mac algorithm.
*
* @param keyid specifies which key to use
* @param message the data for which a signature is to be computed
*/
public byte[] sign(byte[] keyid, byte[] message) {
return signNative(mDrm, mSessionId, keyid, message);
}
/**
* Verify a signature using the CryptoSessions's mac algorithm. Return true
* if the signatures match, false if they do no.
*
* @param keyid specifies which key to use
* @param message the data to verify
* @param signature the reference signature which will be compared with the
* computed signature
*/
public boolean verify(byte[] keyid, byte[] message, byte[] signature) {
return verifyNative(mDrm, mSessionId, keyid, message, signature);
}
};
/**
* Obtain a CryptoSession object which can be used to encrypt, decrypt,
* sign and verify messages or data using the session keys established
* for the session using methods {@link #getKeyRequest} and
* {@link #provideKeyResponse} using a session key server.
*
* @param sessionId the session ID for the session containing keys
* to be used for encrypt, decrypt, sign and/or verify
* @param cipherAlgorithm the algorithm to use for encryption and
* decryption ciphers. The algorithm string conforms to JCA Standard
* Names for Cipher Transforms and is case insensitive. For example
* "AES/CBC/NoPadding".
* @param macAlgorithm the algorithm to use for sign and verify
* The algorithm string conforms to JCA Standard Names for Mac
* Algorithms and is case insensitive. For example "HmacSHA256".
*
* The list of supported algorithms for a DRM engine plugin can be obtained
* using the method {@link #getPropertyString} with the property name
* "algorithms".
*/
public CryptoSession getCryptoSession(byte[] sessionId,
String cipherAlgorithm, String macAlgorithm)
{
return new CryptoSession(this, sessionId, cipherAlgorithm, macAlgorithm);
}
/**
* Contains the opaque data an app uses to request a certificate from a provisioning
* server
*
* @hide - not part of the public API at this time
*/
public final static class CertificateRequest {
private byte[] mData;
private String mDefaultUrl;
CertificateRequest(byte[] data, String defaultUrl) {
mData = data;
mDefaultUrl = defaultUrl;
}
/**
* Get the opaque message data
*/
public byte[] getData() { return mData; }
/**
* Get the default URL to use when sending the certificate request
* message to a server, if known. The app may prefer to use a different
* certificate server URL obtained from other sources.
*/
public String getDefaultUrl() { return mDefaultUrl; }
}
/**
* Generate a certificate request, specifying the certificate type
* and authority. The response received should be passed to
* provideCertificateResponse.
*
* @param certType Specifies the certificate type.
*
* @param certAuthority is passed to the certificate server to specify
* the chain of authority.
*
* @hide - not part of the public API at this time
*/
public CertificateRequest getCertificateRequest(int certType,
String certAuthority)
{
ProvisionRequest provisionRequest = getProvisionRequestNative(certType, certAuthority);
return new CertificateRequest(provisionRequest.getData(),
provisionRequest.getDefaultUrl());
}
/**
* Contains the wrapped private key and public certificate data associated
* with a certificate.
*
* @hide - not part of the public API at this time
*/
public final static class Certificate {
Certificate() {}
/**
* Get the wrapped private key data
*/
public byte[] getWrappedPrivateKey() { return mWrappedKey; }
/**
* Get the PEM-encoded certificate chain
*/
public byte[] getContent() { return mCertificateData; }
private byte[] mWrappedKey;
private byte[] mCertificateData;
}
/**
* Process a response from the certificate server. The response
* is obtained from an HTTP Post to the url provided by getCertificateRequest.
*
* The public X509 certificate chain and wrapped private key are returned
* in the returned Certificate objec. The certificate chain is in PEM format.
* The wrapped private key should be stored in application private
* storage, and used when invoking the signRSA method.
*
* @param response the opaque certificate response byte array to provide to the
* DRM engine plugin.
*
* @throws DeniedByServerException if the response indicates that the
* server rejected the request
*
* @hide - not part of the public API at this time
*/
public Certificate provideCertificateResponse(byte[] response)
throws DeniedByServerException {
return provideProvisionResponseNative(response);
}
private static final native byte[] signRSANative(MediaDrm drm, byte[] sessionId,
String algorithm, byte[] wrappedKey, byte[] message);
/**
* Sign data using an RSA key
*
* @param sessionId a sessionId obtained from openSession on the MediaDrm object
* @param algorithm the signing algorithm to use, e.g. "PKCS1-BlockType1"
* @param wrappedKey - the wrapped (encrypted) RSA private key obtained
* from provideCertificateResponse
* @param message the data for which a signature is to be computed
*
* @hide - not part of the public API at this time
*/
public byte[] signRSA(byte[] sessionId, String algorithm,
byte[] wrappedKey, byte[] message) {
return signRSANative(this, sessionId, algorithm, wrappedKey, message);
}
@Override
protected void finalize() {
native_finalize();
}
public native final void release();
private static native final void native_init();
private native final void native_setup(Object mediadrm_this, byte[] uuid);
private native final void native_finalize();
static {
System.loadLibrary("media_jni");
native_init();
}
}