Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

SecretKeySpec — a key from a byte array

SecretKeySpec wraps existing key bytes and an algorithm name. It copies the data but does not check its cryptographic validity.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new SecretKeySpec(byte[] key, String algorithm)
new SecretKeySpec(byte[] key, int offset, int len, String algorithm)

javax.crypto.spec.SecretKeySpec implements SecretKey and KeySpec, independently of a provider. It wraps raw bytes; it neither generates a key nor derives one from a password.

The constructor copies the entire array or len bytes starting at offset. It does not validate the key for the algorithm. The two-argument overload rejects null and an empty array with IllegalArgumentException.

getAlgorithm() returns the algorithm name, getFormat() returns RAW, and getEncoded() returns a fresh byte copy. Copying does not mean encryption or secure storage.

The example demonstrates both defensive copies. Its fixed bytes are demonstration-only; do not use them as a production key.

Examples

import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] args) {
        byte[] bytes = new byte[16];
        bytes[0] = 7;
        SecretKeySpec key = new SecretKeySpec(bytes, "AES");
        bytes[0] = 9;
        byte[] exported = key.getEncoded();
        exported[0] = 11;
        System.out.println(key.getAlgorithm());
        System.out.println(key.getFormat());
        System.out.println(key.getEncoded()[0]);
    }
}

Result

AES
RAW
7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources