Skip to main content

Overview

The java.security package is the core of the Java security architecture, providing classes and interfaces for security-related functionality including:
  • Message Digests: Cryptographic hash functions (SHA-256, SHA-384, etc.)
  • Digital Signatures: Creating and verifying digital signatures
  • Key Management: Key generation, storage, and retrieval
  • Secure Random: Cryptographically strong random number generation
  • Access Control: Security permissions and policy enforcement
  • Provider Architecture: Pluggable cryptographic service providers

Core Classes

MessageDigest

Provides applications with message digest algorithms (secure one-way hash functions).
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestExample {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        // Create a SHA-256 message digest
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        
        // Update the digest with data
        String data = "Hello, World!";
        md.update(data.getBytes());
        
        // Complete the hash computation
        byte[] digest = md.digest();
        
        // Print the hash in hexadecimal
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        System.out.println("SHA-256 Hash: " + hexString.toString());
    }
}
getInstance(String algorithm)
static MessageDigest
Returns a MessageDigest object that implements the specified algorithm.Parameters:
  • algorithm - the name of the algorithm (e.g., “SHA-256”, “SHA-384”, “SHA-1”)
Throws:
  • NoSuchAlgorithmException - if no provider supports the algorithm
update(byte input)
void
Updates the digest using the specified byte.
update(byte[] input)
void
Updates the digest using the specified array of bytes.
digest()
byte[]
Completes the hash computation and returns the resulting hash value. The digest is reset after this call.
digest(byte[] input)
byte[]
Performs a final update on the digest using the specified array, then completes the digest computation.
Every Java platform implementation is required to support: SHA-1, SHA-256, and SHA-384

Signature

Provides the functionality of a digital signature algorithm for authentication and integrity assurance.
import java.security.*;

public class SignatureExample {
    public static byte[] signData(PrivateKey privateKey, byte[] data) 
            throws Exception {
        // Initialize signature for signing
        Signature sig = Signature.getInstance("SHA256withRSA");
        sig.initSign(privateKey);
        
        // Update with data to sign
        sig.update(data);
        
        // Generate signature
        return sig.sign();
    }
}
getInstance(String algorithm)
static Signature
Returns a Signature object that implements the specified signature algorithm.Standard algorithms include:
  • SHA1withDSA
  • SHA256withDSA
  • SHA256withRSA
  • SHA384withRSA
  • SHA256withECDSA
  • SHA384withECDSA
initSign(PrivateKey privateKey)
void
Initializes this signature object for signing.Throws:
  • InvalidKeyException - if the key is invalid
initVerify(PublicKey publicKey)
void
Initializes this signature object for verification.Throws:
  • InvalidKeyException - if the key is invalid
update(byte[] data)
void
Updates the data to be signed or verified.
sign()
byte[]
Returns the signature bytes of all the data updated. Resets the signature object to its initialized state.Throws:
  • SignatureException - if object is not initialized for signing
verify(byte[] signature)
boolean
Verifies the passed-in signature. Returns true if verified, false otherwise.Throws:
  • SignatureException - if object is not initialized for verification

KeyStore

Represents a storage facility for cryptographic keys and certificates.
import java.security.KeyStore;
import java.io.FileInputStream;

public class KeyStoreExample {
    public static KeyStore loadKeyStore(String path, char[] password) 
            throws Exception {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        
        try (FileInputStream fis = new FileInputStream(path)) {
            ks.load(fis, password);
        }
        
        return ks;
    }
}
getInstance(String type)
static KeyStore
Returns a KeyStore object of the specified type.Standard type: PKCS12 (required on all Java platforms)Throws:
  • KeyStoreException - if no provider supports the specified type
load(InputStream stream, char[] password)
void
Loads this KeyStore from the given input stream. Pass null for stream to create an empty keystore.Throws:
  • IOException - if there is an I/O or format problem
  • NoSuchAlgorithmException - if algorithm for checking integrity cannot be found
  • CertificateException - if certificates cannot be loaded
setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
void
Assigns the given key to the given alias, protecting it with the given password.Throws:
  • KeyStoreException - if keystore has not been initialized or the operation fails
getKey(String alias, char[] password)
Key
Returns the key associated with the given alias, using the given password to recover it.Returns: The requested key, or null if the alias does not exist or does not identify a key-related entry.

SecureRandom

Provides a cryptographically strong random number generator (RNG).
import java.security.SecureRandom;

public class RandomExample {
    public static byte[] generateRandomBytes(int length) {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);
        return bytes;
    }
}
SecureRandom()
constructor
Constructs a secure random number generator (RNG) implementing the default random number algorithm.
getInstance(String algorithm)
static SecureRandom
Returns a SecureRandom object that implements the specified RNG algorithm.Throws:
  • NoSuchAlgorithmException - if no provider supports the specified algorithm
nextBytes(byte[] bytes)
void
Generates a user-specified number of random bytes.
generateSeed(int numBytes)
byte[]
Returns the given number of seed bytes, computed using the seed generation algorithm.Throws:
  • IllegalArgumentException - if numBytes is negative
getInstanceStrong()
static SecureRandom
Returns a SecureRandom object that was selected using the algorithms/providers specified in the securerandom.strongAlgorithms Security property.Throws:
  • NoSuchAlgorithmException - if no algorithm is available
SecureRandom objects are thread-safe. Multiple threads can share a single SecureRandom instance.

Key Interfaces

Key

The top-level interface for all cryptographic keys.
getAlgorithm()
String
Returns the standard algorithm name for this key (e.g., “RSA”, “AES”, “DSA”).
getFormat()
String
Returns the name of the primary encoding format of this key (e.g., “X.509”, “PKCS#8”).
getEncoded()
byte[]
Returns the key in its primary encoding format, or null if the key does not support encoding.

PublicKey

A public key interface (extends Key). This interface contains no methods or constants.

PrivateKey

A private key interface (extends Key). This interface contains no methods or constants.

Provider Architecture

The Java Security API uses a provider-based architecture:
// Uses the default provider
MessageDigest md = MessageDigest.getInstance("SHA-256");

Thread Safety

Most classes in java.security are NOT thread-safe unless explicitly stated:
  • SecureRandom - Thread-safe
  • MessageDigest - Not thread-safe (but can be cloned)
  • Signature - Not thread-safe
  • KeyStore - Not thread-safe

See Also

  • Cryptography APIs - javax.crypto package for encryption/decryption
  • JGSS API - Java Generic Security Services for authentication

Build docs developers (and LLMs) love