str_rot13 / str_shuffle
str_rot13(string $string): string — str_shuffle(string $string): string
经典杂项二件套:ROT13 自逆凯撒位移(应用两次还原原文)与字符串随机重排(手册明示非加密安全——全局 Mt19937、不可注入引擎)。
C C23
C23
/* rot13:经典自逆位移;shuffle 用 rand() 上的 Fisher-Yates——
序列与 libc 实现绑定,因此只断言派生事实。 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void rot13(char *s) { /* 原地,自逆 */
for (; *s; ++s) {
if (*s >= 'a' && *s <= 'z') *s = (char)('a' + (*s - 'a' + 13) % 26);
else if (*s >= 'A' && *s <= 'Z') *s = (char)('A' + (*s - 'A' + 13) % 26);
}
}
int main(void) {
char msg[32] = {0}; /* 零初始化缓冲 */
strcpy(msg, "Hello, World!");
rot13(msg);
printf("%s\n", msg);
rot13(msg);
printf("%s\n", msg); /* 自逆:回到原文 */
/* 播种 shuffle:长度与多重集是可移植事实 */
char cards[7] = "abcdef"; /* 尾部零初始化 */
srand(7);
for (int i = 6 - 1; i > 0; --i) { /* Fisher-Yates */
int j = rand() % (i + 1);
char t = cards[i]; cards[i] = cards[j]; cards[j] = t;
}
printf("%d\n", (int)strlen(cards));
/* 插入排序还原恒等排列 */
for (int i = 1; cards[i]; ++i) {
char key = cards[i];
int j = i - 1;
while (j >= 0 && cards[j] > key) { cards[j + 1] = cards[j]; --j; }
cards[j + 1] = key;
}
printf("%s\n", cards);
return 0;
}
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
C++ C++26
C++26
// rot13 走 unsigned char 算术;shuffle 用可播种引擎
// (std::mt19937——可注入,不像 PHP 的全局 str_shuffle)。
#include <algorithm>
#include <iostream>
#include <random>
#include <string>
static char rot13c(char c) { // 自逆 ASCII 位移
if (c >= 'a' && c <= 'z') return (char)('a' + (c - 'a' + 13) % 26);
if (c >= 'A' && c <= 'Z') return (char)('A' + (c - 'A' + 13) % 26);
return c;
}
int main() {
std::string msg = "Hello, World!";
std::transform(msg.begin(), msg.end(), msg.begin(), rot13c);
std::cout << msg << "\n";
std::transform(msg.begin(), msg.end(), msg.begin(), rot13c);
std::cout << msg << "\n"; // 自逆
std::string cards = "abcdef";
std::mt19937 rng(7); // 可播种引擎:序列可复现
std::shuffle(cards.begin(), cards.end(), rng);
std::cout << cards.size() << "\n";
std::sort(cards.begin(), cards.end());
std::cout << cards << "\n"; // 排列证明
}
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
C# v11.0.100
v11.0.100
// rot13 走 char 算术;shuffle 注入 Random(7)——序列可复现
// (PHP 的 str_shuffle 不可注入)。
using System.Linq;
static char Rot13(char c) => c switch { // 自逆 ASCII 位移
>= 'a' and <= 'z' => (char)('a' + (c - 'a' + 13) % 26),
>= 'A' and <= 'Z' => (char)('A' + (c - 'A' + 13) % 26),
_ => c };
var msg = "Hello, World!";
msg = new string(msg.Select(Rot13).ToArray());
Console.WriteLine(msg);
msg = new string(msg.Select(Rot13).ToArray());
Console.WriteLine(msg); // 自逆
var cards = "abcdef".ToList();
var rng = new Random(7); // 注入种子:序列可复现
for (int i = cards.Count - 1; i > 0; --i) { // Fisher-Yates
int j = rng.Next(i + 1);
(cards[i], cards[j]) = (cards[j], cards[i]);
}
Console.WriteLine(cards.Count);
Console.WriteLine(string.Concat(cards.OrderBy(c => c))); // 排列证明
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
Go v1.27.4
v1.27.4
// rot13 逐字节映射;shuffle 用注入的 rand.Rand 源——序列可复现
// (PHP 的 str_shuffle 不可注入)。
package main
import (
"fmt"
"math/rand"
"sort"
"strings"
)
func rot13(s string) string { // 自逆 ASCII 位移
var b strings.Builder
for _, c := range []byte(s) {
if c >= 'a' && c <= 'z' { c = 'a' + (c-'a'+13)%26 }
if c >= 'A' && c <= 'Z' { c = 'A' + (c-'A'+13)%26 }
b.WriteByte(c)
}
return b.String()
}
func main() {
msg := rot13("Hello, World!")
fmt.Println(msg)
fmt.Println(rot13(msg)) // 自逆
cards := strings.Split("abcdef", "")
rng := rand.New(rand.NewSource(7)) // 注入种子:可复现
rng.Shuffle(len(cards), func(i, j int) { cards[i], cards[j] = cards[j], cards[i] })
fmt.Println(len(cards))
sort.Strings(cards)
fmt.Println(strings.Join(cards, "")) // 排列证明
}
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
Java v27.0.1
v27.0.1
// rot13 走 char 算术;Collections.shuffle 注入 Random(7)——
// 序列可复现(PHP 的 str_shuffle 不可注入)。
import java.util.*;
public class Main {
static char rot13(char c) { // 自逆 ASCII 位移
if (c >= 'a' && c <= 'z') return (char)('a' + (c - 'a' + 13) % 26);
if (c >= 'A' && c <= 'Z') return (char)('A' + (c - 'A' + 13) % 26);
return c;
}
static String rot13(String s) {
var b = new StringBuilder();
for (char c : s.toCharArray()) b.append(rot13(c));
return b.toString();
}
public static void main(String[] args) {
String msg = rot13("Hello, World!");
System.out.println(msg);
System.out.println(rot13(msg)); // 自逆
List<String> cards = new ArrayList<>(Arrays.asList("abcdef".split("")));
Collections.shuffle(cards, new Random(7)); // 注入种子
System.out.println(cards.size());
Collections.sort(cards);
System.out.println(String.join("", cards)); // 排列证明
}
}
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
JavaScript v26.13.1
v26.13.1
// rot13 走正则映射;Math.random 上的 Fisher-Yates——不可播种
// (标准没有播种 API),因此只断言派生事实。
function rot13(s) { // 自逆 ASCII 位移
return s.replace(/[a-z]/gi, (c) => {
const base = c <= "Z" ? 65 : 97;
return String.fromCharCode(base + ((c.charCodeAt(0) - base + 13) % 26));
});
}
const msg = rot13("Hello, World!");
console.log(msg);
console.log(rot13(msg)); // 自逆
const cards = "abcdef".split("");
for (let i = cards.length - 1; i > 0; --i) { // Fisher-Yates
const j = Math.floor(Math.random() * (i + 1));
[cards[i], cards[j]] = [cards[j], cards[i]];
}
console.log(cards.length);
console.log(cards.sort().join("")); // 排列证明
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
PHP v8.6.0
v8.6.0
// str_rot13 - 凯撒位移 13,自逆:应用两次还原原文。
// str_shuffle - 字符串的一个排列;按 PHP 手册明示它**非加密安全**
// (全局 Mt19937 状态)且不可播种——断言派生事实而非具体排列。
echo str_rot13("Hello, World!"), "\n";
echo str_rot13(str_rot13("round trip")), "\n";
$shuffled = str_shuffle("abcdef");
echo strlen($shuffled), "\n";
$sorted = str_split($shuffled);
sort($sorted);
echo implode("", $sorted), "\n"; // 排列证明:排序还原 "abcdef"
输出
Uryyb, Jbeyq! round trip 6 abcdef
Python v3.15.2
v3.15.2
# codecs 的 "rot13" 是直接孪生;random 可播种,播种后的 shuffle
# 可复现(PHP 的 str_shuffle 完全不可播种)。
import codecs
import random
print(codecs.encode("Hello, World!", "rot13"))
print(codecs.encode(codecs.encode("round trip", "rot13"), "rot13")) # 自逆
cards = list("abcdef")
random.seed(7) # 播种:序列可复现
random.shuffle(cards)
print(len(cards))
print("".join(sorted(cards))) # 排列证明
输出
Uryyb, Jbeyq! round trip 6 abcdef
Rust v1.99.1
v1.99.1
// rot13 逐字节映射;shuffle 用可播种的 xorshift——std 无随机数,
// 小型可注入引擎演示种子 → 可复现序列的契约。
struct Xorshift(u64); // 极简播种引擎
impl Xorshift {
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
}
fn rot13(s: &str) -> String { // 自逆 ASCII 位移
s.bytes()
.map(|c| match c {
b'a'..=b'z' => b'a' + (c - b'a' + 13) % 26,
b'A'..=b'Z' => b'A' + (c - b'A' + 13) % 26,
other => other,
})
.map(|c| c as char)
.collect()
}
fn main() {
let msg = rot13("Hello, World!");
println!("{}", msg);
println!("{}", rot13(&msg)); // 自逆
let mut cards: Vec<char> = "abcdef".chars().collect();
let mut rng = Xorshift(7); // 注入种子:可复现
for i in (1..cards.len()).rev() { // Fisher-Yates
let j = (rng.next() % (i as u64 + 1)) as usize;
cards.swap(i, j);
}
println!("{}", cards.len());
cards.sort();
println!("{}", cards.into_iter().collect::<String>()); // 排列证明
}
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
TypeScript v26.13.1
v26.13.1
// 同 JavaScript:rot13 映射 + 不可播种的 Fisher-Yates,
// 因此只断言派生事实(长度、排序还原)。
function rot13(s: string): string {
return s.replace(/[a-z]/gi, (c: string) => {
const base: number = c <= "Z" ? 65 : 97;
return String.fromCharCode(base + ((c.charCodeAt(0) - base + 13) % 26));
});
}
const msg: string = rot13("Hello, World!");
console.log(msg);
console.log(rot13(msg));
const cards: string[] = "abcdef".split("");
for (let i = cards.length - 1; i > 0; --i) {
const j: number = Math.floor(Math.random() * (i + 1));
[cards[i], cards[j]] = [cards[j], cards[i]];
}
console.log(cards.length);
console.log(cards.sort().join(""));
输出
Uryyb, Jbeyq! Hello, World! 6 abcdef
语言差异说明
ROT13:位移 13 的凯撒密码,自逆性 rot13(rot13(x)) === x 因为 13+13=26;只映射 ASCII 字母,数字与符号原样;PHP 内置 str_rot13,Python 有 codecs.encode(s, "rot13"),其余语言手写。str_shuffle:任务描述"shuffle 用 CSPRNG"与手册不符——PHP 手册明确警告它「不生成加密安全值」,7.1 起用的是全局 Mt19937 实例(与 mt_rand/shuffle 共享状态,mt_srand 播种后 str_shuffle 输出事实上可复现——但 API 层面不收 seed 参数、不可注入引擎),需要加密安全随机请用 Random\Randomizer + Random\Engine\Secure(见 randomizer 条目)或 random_bytes/random_int;断言用派生事实(长度不变 + 排序还原多重集),不断言具体排列——这是随机输出的确定性测试标准做法。各语言对照:Java/C#/Go/Rust/C 都能注入引擎(new Random(7)/rand.NewSource(7)/自实现种子)拿到可复现序列——正是 PHP str_shuffle 做不到的;JavaScript/TS 的 Math.random 与 PHP 同病:不可播种(标准无 API),只能走派生事实断言。教学锚点:随机性测试三律——不测具体序列、测守恒量(长度/多重集)、需要可复现时注入引擎(语言支持与否见各 notes)。