Secret Key Authentication Examples

These scripts generate temporary credentials for TURN authentication. Written in Python, JavaScript (Node.js), Perl, and Go, each script creates a username (timestamp:user) and password (HMAC-SHA1 with a shared secret) valid for 24 hours.

To use, replace `your_shared_secret` with your TURN server's secret and `relay1.expressturn.com:3480` the TURN server and port you would like to use. The output includes credentials and a sample WebRTC ICE configuration.

Pick your preferred language and use these simple scripts for secure TURN authentication in your WebRTC app.

Python


#!/usr/bin/env python3
import hmac
import hashlib
import time
import base64

# Configuration
TURN_SECRET = "your_shared_secret"  # Shared secret from TURN server
TTL = 86400                        # Time-to-live in seconds (24 hours)

# Generate TURN credentials
def generate_turn_credentials(username):
    # Current timestamp
    timestamp = int(time.time()) + TTL
    
    # Combine timestamp with username
    turn_username = f"{timestamp}:{username}"
    
    # Generate password using HMAC-SHA1 and encode in Base64
    hmac_obj = hmac.new(
        TURN_SECRET.encode('utf-8'),
        turn_username.encode('utf-8'),
        hashlib.sha1
    )
    password = base64.b64encode(hmac_obj.digest()).decode('utf-8')
    
    return turn_username, password

# Generate and display credentials
user = "username"
turn_username, turn_password = generate_turn_credentials(user)

# Formatted output using triple-quoted string
print(f"""TURN Credentials
----------------------------------------
Username: {turn_username}
Password: {turn_password}
TTL     : {TTL} seconds
----------------------------------------

Example WebRTC ICE Configuration
{{
  "iceServers": [
    {{
      "urls": ["turn:relay1.expressturn.com:3480"],
      "username": "{turn_username}",
      "credential": "{turn_password}"
    }}
  ]
}}
""")
            

JavaScript (Node.js)


#!/usr/bin/env node
const crypto = require('crypto');

// Configuration
const TURN_SECRET = "your_shared_secret"; // Shared secret from TURN server
const TTL = 86400;                       // Time-to-live in seconds (24 hours)

// Generate TURN credentials
function generateTurnCredentials(username) {
    // Current timestamp
    const timestamp = Math.floor(Date.now() / 1000) + TTL;
    
    // Combine timestamp with username
    const turnUsername = `${timestamp}:${username}`;
    
    // Generate password using HMAC-SHA1 and encode in Base64
    const password = crypto.createHmac('sha1', TURN_SECRET)
                          .update(turnUsername)
                          .digest('base64');
    
    return [turnUsername, password];
}

// Generate and display credentials
const user = "username";
const [turnUsername, turnPassword] = generateTurnCredentials(user);

// Formatted output using template literal
console.log(`TURN Credentials
----------------------------------------
Username: ${turnUsername}
Password: ${turnPassword}
TTL     : ${TTL} seconds
----------------------------------------

Example WebRTC ICE Configuration
{
  "iceServers": [
    {
      "urls": ["turn:relay1.expressturn.com:3480"],
      "username": "${turnUsername}",
      "credential": "${turnPassword}"
    }
  ]
}
`);
            

Perl


#!/usr/bin/perl
use strict;
use warnings;
use Digest::HMAC_SHA1 qw(hmac_sha1);
use MIME::Base64 qw(encode_base64);
use Time::HiRes qw(time);

# Configuration
my $turn_secret = "your_shared_secret";  # Shared secret from TURN server
my $ttl = 86400;                        # Time-to-live in seconds (24 hours)

# Generate TURN credentials
sub generate_turn_credentials {
    my ($username) = @_;
    
    # Current timestamp
    my $timestamp = int(time()) + $ttl;
    
    # Combine timestamp with username
    my $turn_username = "$timestamp:$username";
    
    # Generate password using HMAC-SHA1 and encode in Base64
    my $hmac = hmac_sha1($turn_username, $turn_secret);
    my $password = encode_base64($hmac, '');
    
    return ($turn_username, $password);
}

# Generate and display credentials
my $user = "username";
my ($turn_username, $turn_password) = generate_turn_credentials($user);

# Formatted output using heredoc
print <<'EOF';
TURN Credentials
----------------------------------------
Username: $turn_username
Password: $turn_password
TTL     : $ttl seconds
----------------------------------------

Example WebRTC ICE Configuration
{
  "iceServers": [
    {
      "urls": ["turn:relay1.expressturn.com:3480"],
      "username": "$turn_username",
      "credential": "$turn_password"
    }
  ]
}
EOF
            

Go


package main

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"time"
)

// Configuration
const turnSecret = "your_shared_secret" // Shared secret from TURN server
const ttl = 86400                       // Time-to-live in seconds (24 hours)

// Generate TURN credentials
func generateTurnCredentials(username string) (string, string) {
	// Current timestamp
	timestamp := time.Now().Unix() + ttl

	// Combine timestamp with username
	turnUsername := fmt.Sprintf("%d:%s", timestamp, username)

	// Generate password using HMAC-SHA1 and encode in Base64
	mac := hmac.New(sha1.New, []byte(turnSecret))
	mac.Write([]byte(turnUsername))
	password := base64.StdEncoding.EncodeToString(mac.Sum(nil))

	return turnUsername, password
}

func main() {
	user := "username"
	turnUsername, turnPassword := generateTurnCredentials(user)

	// Formatted output
	fmt.Printf(`TURN Credentials
----------------------------------------
Username: %s
Password: %s
TTL     : %d seconds
----------------------------------------

Example WebRTC ICE Configuration
{
  "iceServers": [
    {
      "urls": ["turn:relay1.expressturn.com:3480"],
      "username": "%s",
      "credential": "%s"
    }
  ]
}
`, turnUsername, turnPassword, ttl, turnUsername, turnPassword)
}