first commit

This commit is contained in:
Mauve
2026-09-08 17:20:27 +08:00
commit a7f2e0ca01
752 changed files with 111259 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
{
"version" : "1.0",
"configurations" : [
{
"bundleId" : "com.mgm.mcrm",
"certificateFile" : "/Users/liuchong/Downloads/ios_cert_test/private_key_250619.p12",
"certificateProfileFile" : "/Users/liuchong/Downloads/ProfileMgmMCRM_250619.mobileprovision",
"playground" : "custom",
"runSignStatus" : 1,
"type" : "uni-app:APP-PLUS"
},
{
"app-plus" : {
"launchtype" : "local"
},
"mp-weixin" : {
"launchtype" : "local"
},
"type" : "uniCloud"
},
{
"playground" : "standard",
"type" : "uni-app:APP-PLUS_simulator"
},
{
"bundleId" : "com.mgm.mcrm",
"certificateFile" : "/Users/liuchong/Downloads/ios_cert_test/private_key_250619.p12",
"certificateProfileFile" : "/Users/liuchong/Downloads/ios_cert_test/profileMCRM_250709.mobileprovision",
"playground" : "custom",
"runSignStatus" : 1,
"type" : "uni-app:app-ios"
},
{
"openVueDevtools" : true,
"type" : "uni-app:h5"
}
]
}
+661
View File
@@ -0,0 +1,661 @@
<script>
import config from './common/config.js'
import {writeDebugLog,getSettingByKey,getSettings,verifyToken,logout} from './api/commonApi.js'
import { getCfgSettingByKey } from './api/configApi.js'
import store from './store/index.js'
import FixedCoordinateConverter from './common/fixedCoordinateConverter.js'
import {refreshToken} from './api/commonApi.js'
import dayjs from './uni_modules/uview-ui/libs/util/dayjs.js';
import { decryptCfgSettingValue } from './common/cfgSettingCrypto.js';
// #ifdef APP-PLUS
var networkModule = uni.requireNativePlugin("NetworkUtils-NetworkUtilsModule")
// #endif
export default {
data() {
return {
timer: null, // 定时器引用
backgroundTaskId: 0 // iOS 后台任务ID
}
},
onLaunch: function() {
this.initApp();
// #ifdef APP-PLUS
this.checkJailbreak();
uni.getLocation({
type: 'wgs84',
success: (res) => {}
});
/*plus.globalEvent.addEventListener('newintent', (e)=>{
var args= plus.runtime.arguments;
console.log(args)
uni.showToast({
title: 'APP LAUNCH-newintent'
});
if(args){
var code = this.getSchemeParam('code',args)
uni.showToast({
title: code
});
uni.redirectTo({
url:'/pages/login/login?code='+encodeURIComponent(code)
})
}
});*/
// #endif
},
onShow: function() {
//console.log("APP.vue:onShow()");
// 监听网络状态变化
/*uni.onNetworkStatusChange(function(res) {
if (res.isConnected) {
if (res.networkType === 'wifi') {
console.log('网络已连接,并且是Wi-Fi');
} else {
console.log('网络已连接,但不是Wi-Fi');
}
} else {
console.log('网络已断开');
}
});*/
// #ifdef APP-PLUS
this.getSettingByKey('MACAU_STRING');
// #endif
},
onHide: function() {
// #ifdef APP-PLUS
this.stopTimer();
// #endif
},
beforeDestroy() {
// 组件销毁时清理资源
// #ifdef APP-PLUS
this.stopTimer();
// #endif
},
methods:{
startTimer() {
// 先清除可能存在的旧定时器
this.stopTimer();
// 每60秒执行一次目标方法
this.timer = setInterval(() => {
this.checkLocationVPNByTimer(null);
// this.checkToken()
}, 10000);
},
// 停止定时器
stopTimer() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
},
checkLocationVPNByTimer(type){
let url = this.getCurrentUrl();
if(
url!==null && url!==undefined
&& url.indexOf('logout')==-1
&& url.indexOf('Logout')==-1
&& url.indexOf('login')==-1
&& url.indexOf('Login')==-1
&& url.indexOf('setting')==-1
&& url.indexOf('regionRestrict')==-1
&& url.indexOf('callback')==-1
&& url.indexOf('adfs')==-1
){
let siteData = uni.getStorageSync("siteData");
//只有外网才检查
if(siteData!==undefined && siteData!==null && siteData.internalTag===false)
{
this.checkLocationAndVPN(type);
}
}
},
async getSettingByKey(key){
try{
let params = {
keyName : key
}
const res = await getCfgSettingByKey(params);
const cfg = new config();
if (res && res.data && res.data.keyValues) {
res.data.keyValues = await decryptCfgSettingValue(res.data.keyValues, cfg.allowKey);
}
this.macauString = res.data;
uni.setStorageSync("macauString",this.macauString.keyValues);
}catch(e){
console.log(e);
}finally{
this.startTimer();
}
},
getCurrentUrl(){
const pages = getCurrentPages();
if (!pages.length) return null;
// 获取当前页面实例
const currentPage = pages[pages.length - 1];
// 获取页面路径(如:pages/index/index)
const route = currentPage.route;
// 获取页面参数对象(如:{ id: 123 })
const options = currentPage.options;
// 拼接完整路径(带参数)
let url = `/${route}`;
const query = Object.keys(options).map(key =>
`${key}=${encodeURIComponent(options[key])}`
).join('&');
if (query) url += `?${query}`;
return url;
},
getSchemeParam(name,scheme) {
var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
if (reg.test(scheme)) return unescape(RegExp.$2.replace(/\+/g, " "));
return "";
},
async initApp(){
// #ifdef APP-PLUS
plus.screen.lockOrientation("portrait");
// #endif
await this.initCfg(); // 获取配置参数
},
// 初始化方法
async initCfg(){
// 配置站点信息
const cfg = new config();
// 判断外网还是内网
// 現在內外網改成由後端判斷
// 如果是外网
const userData = uni.getStorageSync('userData');
const oldSiteData = uni.getStorageSync('siteData');
let oldDebugMode = cfg.debugMode;
let userId = "";
if(oldSiteData!=undefined && oldSiteData!=null && oldSiteData!=''){
oldDebugMode = oldSiteData.debugMode;
}
if(userData!=undefined && userData!=null && userData!=''){
userId = userData.userId;
}
let isInternal = true;
let macauString = "";
let siteData = {
internalUrl : cfg.internalUrl,
externalUrl : cfg.externalUrl,
apiPath : cfg.apiPath,
internalTag : isInternal,
macauIp: true,
internalSSOUrl: cfg.internalSSOUrl,
externalSSOUrl: cfg.externalSSOUrl,
version:cfg.version,
debugMode: true,
mockSSO:false,
mockTPD:false
};
store.dispatch('setSiteData',siteData);
uni.setStorageSync('siteData', siteData);
// 初始化uview http请求配置
uni.$u.http.setConfig((config) => {
if(isInternal){
config.baseURL = store.state.siteData.internalUrl + store.state.siteData.apiPath;
}
else{
config.baseURL = store.state.siteData.externalUrl + store.state.siteData.apiPath;
}
config.custom.auth = true;
config.custom.origin = cfg.originUrl;
config.custom.appId = cfg.appId;
config.custom.allowKey = cfg.allowKey;
return config;
})
//this.writeLog(userId,"app_init","","[APP][App.vue][initCfg][Begin]","[SiteData]" + JSON.stringify(siteData),"",0,false);
// 获取配置设备信息
let safeArea = false;
await uni.getSystemInfo({
success: res => {
//console.log(res.statusBarHeight);
if (res.safeArea.top > 20) {
//x及以上的异形屏top为44,非异形屏为20
safeArea = true;
}
}
})
let info = uni.getSystemInfoSync()//获取设备信息
let statusBarHeight = info.statusBarHeight
let windowWidth = info.windowWidth
let windowHeight = info.windowHeight
const deviceData = {
statusBarHeight : statusBarHeight,
windowWidth : windowWidth,
windowHeight : windowHeight,
saveArea : safeArea,
};
store.dispatch('setDeviceData',deviceData);
uni.setStorageSync('deviceData', deviceData);
//this.writeLog(userId,"app_init","","[APP][App.vue][initCfg][End]","[DeviceData]"+JSON.stringify(deviceData),"",0,false);
this.$isResolve();
},
// 全局函数,main.js中注册
// 判断login
isLogin(){
let loginTag = false;
let user = uni.getStorageSync('userData');
let site = uni.getStorageSync('siteData');
let timeOut = uni.getStorageSync('timeOut');
let token = uni.getStorageSync("token")
let clientId = uni.getStorageSync("clientId")
var now = Math.floor(new Date().getTime() / 1000);
if(user){
loginTag = user.loginTag;
}
if(token==undefined||token==null||token==""||clientId==undefined||clientId==null||clientId==""){
loginTag = false;
}
if(now >= timeOut) loginTag = false;
if(loginTag!==true){
uni.removeStorageSync("userData");
uni.removeStorageSync("token");
uni.removeStorageSync("idToken");
this.navTo('/pages/login/login',2,false);
}
},
//判断是否有Permission
redirectByPermission(userData,needRedirect){
if(userData!==null && userData!==undefined){
if(userData.canViewDashboard){
this.navTo('/pages/dashboard/dashboard',1,false);
}else if(userData.canViewTodoList){
this.navTo('/salessupport/todoList/todoList',1,false);
}else if(userData.canViewBooking){
this.navTo('/pages/findPlayer/findPlayer',1,false);
}else{
this.navTo('/pages/setting/setting',1,false);
}
}
},
//根据Permission显示Tabbar
showTabbarByPermission(userData){
if(userData!==null && userData!==undefined){
console.log('Setting Tabbar');
if(userData.canViewDashboard){
uni.setTabBarItem({
index:0,
visible:true
});
}
if(userData.canViewTodoList){
uni.setTabBarItem({
index:1,
visible:true
});
}
if(userData.canViewBooking){
uni.setTabBarItem({
index:2,
visible:true
});
}
}
},
// 返回
navBack(delta){
if(delta){
uni.navigateBack({
delta: delta
});
}
else{
uni.navigateBack();
}
},
checkJailbreak(){
// 调用同步方法
networkModule.checkJailbreakAsync({
}, (result) => {
if(result.status === 'success'){
if(result.isJailbroken==true){
this.stopTimer();
this.navTo('/pages/disableApp/disableApp',0,false); //2
}
}
});
},
checkLocationAndVPN(type){
let objVPNData = this.checkVPNOpen();
let isOpenVPN = false;
let ipAddress = "";
let userId = "";
let userData = uni.getStorageSync("userData");
if(userData!==undefined && userData!==null && userData!=="" && userData.userId!==undefined && userData.userId!==null && userData.userId!==""){
userId = userData.userId;
}
this.writeLog(userId,"getLocationVPN","","[APP][App.vue][checkLocationAndVPN][Success]step1","","",1,false);
if(objVPNData === null)
{
isOpenVPN = null;
}
else
{
isOpenVPN = objVPNData.isVPNConnected;
ipAddress = objVPNData.ipAddress;
}
this.writeLog(userId,"getLocationVPN","","[APP][App.vue][checkLocationAndVPN][Success]vpn:"+isOpenVPN,"","",1,false);
//检查如果使用了VPN或不在澳门
// let isInMacau = this.checkInMacau();
// 在页面中请求定位权限
uni.getLocation({
type: 'wgs84',
success: (res) => {
this.writeLog(userId,"getLocationVPN","","[APP][App.vue][checkLocationAndVPN][Success]step3","","",1,false);
const converter = new FixedCoordinateConverter();
//console.log('经纬度数据:', res);
const gcjPoint = converter.wgs84ToGcj02Fixed(res.latitude, res.longitude);
//console.log(gcjPoint);
networkModule.getCityNameByCoordinate({
latitude: gcjPoint.lat,
longitude: gcjPoint.lng
//latitude: res.latitude,
//longitude: res.longitude
//模拟澳门IP
// latitude: 22.142149,
// longitude: 113.562888,
//模拟澳门IP
}, (result) => {
let msgType = "0";
if (result.status === 'success') {
let isInMacau = (result.isInMacau == 'YES')? true:false;
/*uni.showToast({
title:'城市:' + result.city + ',地址:'+result.fullAddress,
icon: "none"
})*/
this.writeLog(userId,"getLocationVPN","","[APP][App.vue][checkLocationAndVPN][Success]"+result.isInMacau+ ", city:"+result.city+ ", address:"+result.fullAddress+ ", IP address:"+ipAddress,"","",1,false);
/*uni.showToast({
title:'是否在澳门:'+isInMacau+',是否使用VPN:'+isOpenVPN,
icon: "none"
})*/
if(!isInMacau){
let macauStringList = uni.getStorageSync("macauString").split(";");
for(let i=0;i<macauStringList.length;i++){
if(result.fullAddress.indexOf(macauStringList[i]) !== -1
&& macauStringList[i] !== "" && macauStringList[i] !== null){
isInMacau = true;
break;
}else{
isInMacau = false;
}
}
}
//isInMacau = true;
// isOpenVPN = false;
if((isInMacau===null||isInMacau===undefined) && isOpenVPN!==null){ //调用地址出错
msgType = "1";
}
else if((isInMacau!==null&&isInMacau!==undefined) && isOpenVPN===null){ //调用VPN出错
msgType = "2";
}
else if((isInMacau===null||isInMacau===undefined) && isOpenVPN===null){ //调用地址和VPN出错
msgType = "3";
}
else if(isInMacau === false && isOpenVPN===false){ //不在澳门,没开了VPN,不通过
msgType = "4";
}
else if(isInMacau === true && isOpenVPN===true){ //在澳门,但是开了VPN,不通过
msgType = "5";
}
else if(isInMacau === false && isOpenVPN===true){ //不在澳门,开了VPN,不通过
msgType = "6";
}
else if(isInMacau===null||isInMacau===undefined){ //调用地址出错
msgType = "1";
}
//重新调用isMacauApi 获取定位信息
let siteData = uni.getStorageSync("siteData");
this.writeLog(userId,"getLocationVPN","","[APP][App.vue][checkLocationAndVPN][Success]Site data:"+JSON.stringify(siteData)+"IsInMacau:"+isInMacau,"","",1,false);
if(siteData.internalTag==false && siteData.macauIp == false){
msgType = "7";
}
} else {
msgType = "1";
/*uni.showToast({
title:'错误:' + result.error + ", latitude:"+res.latitude+ ", longitude:"+res.longitude,
icon: "none"
})*/
this.writeLog(userId,"getLocationVPN","","[APP][App.vue][checkLocationAndVPN][Error]"+result.error+ ", old latitude:"+res.latitude+ ", old longitude:"+res.longitude+ ", latitude:"+gcjPoint.lat+ ", longitude:"+gcjPoint.lng+ ", IP address:"+ipAddress,"","",1,false);
}
if(msgType!=="0" && type!==true){
//跳转去一个页面
this.navTo('/pages/regionRestrict/regionRestrict?type='+msgType,0,false); //2
}
if(msgType==="0" && type === true){ // retry的情况
this.navBack();
}
else if(msgType==="0" && type === false){ //登录的情况
let userData= uni.getStorageSync("userData");
this.redirectByPermission(userData,true);
}
});
},
fail: (err) => {
/*uni.showToast({
title:'uni.getLocation fail',
icon: "none"
});*/
this.writeLog(userId,"getLocationVPN","","[APP][App.vue][checkLocationAndVPN][Error]uni.getLocation fail"+ ", IP address:"+ipAddress,"","",1,false);
this.navTo('/pages/regionRestrict/regionRestrict?type=1',0,false);
}
});
},
checkVPNOpen() {
// 调用同步方法
let ret = networkModule.checkVPNSync({'testVPN': 'Sync'})
let respData = JSON.parse(ret);
if(respData.status === 'success'){
return respData;
}else{
return null;
}
/*uni.showToast({
title:'是否连接VPN:' + respData.isVPNConnected + ',IP地址:'+ respData.ipAddress + ',状态:'+ respData.status,
icon: "none"
})*/
},
// 跳转
async writeLog(userId,eventCode,transactionId,description,requestBody,responseBody,successTag,debugTag){
if(debugTag===undefined || debugTag===false){
const siteData = uni.getStorageSync('siteData');
if(siteData.debugMode==false){
return;
}
}
let obj = {};
obj.loginId = userId;
obj.eventCode = eventCode;
obj.transId = transactionId;
obj.logDesc = description;
obj.requestBody = requestBody;
obj.responseBody = responseBody;
obj.tagSuccess = successTag;
//console.log(obj);
try{
const response = await writeDebugLog(obj);
}
catch(e){
console.error(e.errMsg);
}
},
async logout(){
let siteData = uni.getStorageSync("siteData");
let userData = uni.getStorageSync("userData");
uni.showLoading({
title: this.$t("common.loading")
});
try{
let params = {};
const res = await logout(params);
if(res.success == true){
if(res.data !== null){
uni.setTabBarItem({
index:0,
visible:false
});
uni.setTabBarItem({
index:1,
visible:false
});
uni.setTabBarItem({
index:2,
visible:false
});
if(siteData.mockSSO==false&&!siteData.internalTag){
//this.logoutWithADFSApp()
uni.redirectTo({
url:'/pages/azureLogout/azureLogout'
});
}else{
uni.removeStorageSync("userData");
uni.removeStorageSync("token");
uni.removeStorageSync("idToken");
this.navTo('/pages/login/login',2,false);
}
}
}else{
if(siteData.mockSSO==false&&!siteData.internalTag){
//this.logoutWithADFSApp()
uni.redirectTo({
url:'/pages/azureLogout/azureLogout'
});
}else{
uni.removeStorageSync("userData");
uni.removeStorageSync("token");
uni.removeStorageSync("idToken");
this.navTo('/pages/login/login',2,false);
}
}
}catch(e){
console.error(e);
uni.$u.toast(e.errMsg,5000);
await this.writeLog(userData.userId,"logout","","[APP][setting.vue][logout][Catch Exception]"+e.errMsg,"","",1,false);
}finally{
uni.hideLoading();
}
},
async navTo(url,type,auth){
let token = uni.getStorageSync('token');
if(token){
const response = await verifyToken({});
if(response.status==200){
}else{
console.error(response)
}
}
if(auth==true){
let user = uni.getStorageSync('userData');
let loginTag = false;
if(user){
loginTag = user.loginTag;
}
if(loginTag==true){
if(type===1)
{
uni.switchTab({
url
})
}
else if(type===2)
{
uni.redirectTo({
url
})
}else{
uni.navigateTo({
url
})
}
}else{
uni.showModal({
title: this.$t("common.warning"),
content: this.$t("common.loginAlert"),
cancelText: this.$t("common.cancel"), // 取消按钮的文字
confirmText: this.$t("common.login"), // 确认按钮的文字
showCancel: true, // 是否显示取消按钮,默认为 true
confirmColor: '#C39A4B',
success: (res) => {
if(res.confirm) {
uni.redirectTo({
url:'/pages/login/login'
})
} else {
return;
}
}
})
return;
}
}
else{
if(type===1)
{
uni.switchTab({
url
})
}
else if(type===2)
{
uni.redirectTo({
url
})
}else{
uni.navigateTo({
url
})
}
}
},
kickout() {
uni.removeStorageSync("userData");
uni.removeStorageSync("token");
uni.removeStorageSync("idToken");
uni.removeStorageSync("clientId");
uni.redirectTo({
url:'/pages/login/login'
})
},
checkToken(){
let now = Math.floor(new Date().getTime() / 1000);
let tokenTime = uni.getStorageSync("tokenTime");
let token = uni.getStorageSync("token")
//4 min refresh token
if(token!="" && now - tokenTime>240){
let oldToken = uni.getStorageSync("token");
if (oldToken !== null && oldToken !== '') {
return refreshToken({})
.then((data) => {
uni.setStorageSync("token",data.token);
uni.setStorageSync("tokenTime",dayjs().unix());
return Promise.resolve(true)
})
.catch(error => {
this.kickout()
})
} else {
this.kickout()
}
}
}
}
}
</script>
<style lang="scss">
/*每个页面公共css */
@import './static/css/custom.scss';
@import "@/uni_modules/uview-ui/index.scss";
</style>
+9
View File
@@ -0,0 +1,9 @@
export const getApprovalReason = (params, config = {}) => uni.$u.http.post('/app/approval/get_reason', params, config)
export const getApprover = (params, config = {}) => uni.$u.http.post('/app/approval/get_approver', params, config)
export const getApprovalList = (params, config = {}) => uni.$u.http.post('/app/approval/approval_list', params, config)
export const getApprovalCount = (params, config = {}) => uni.$u.http.post('/app/approval/get_approval_count', params, config)
export const getApprovalData = (params, config = {}) => uni.$u.http.post('/app/approval/get_approval_data', params, config)
export const rejectApproval = (params, config = {}) => uni.$u.http.post('/app/approval/reject_approval', params, config)
export const submitApproval = (params, config = {}) => uni.$u.http.post('/app/approval/submit_approval', params, config)
export const batchSubmitApproval = (params, config = {}) => uni.$u.http.post('/app/approval/batch_submit_approval', params, config)
export const batchSubmitReject = (params, config = {}) => uni.$u.http.post('/app/approval/batch_submit_reject', params, config)
+11
View File
@@ -0,0 +1,11 @@
export const getBookingsMock = (params, config = {}) => uni.$u.http.post('/app/booking/get_bookings_by_nameId', params, config)
export const saveBooking = (params, config = {}) => uni.$u.http.post('/app/booking/create', params, config)
export const getBookings = (params, config = {}) => uni.$u.http.post('/app/bookings/search_optimize', params, config)
export const getBookingByConf = (params, config = {}) => uni.$u.http.post('/app/booking/get_booking_by_conf', params, config)
export const getBookingById = (params, config = {}) => uni.$u.http.post('/app/booking/get_booking_by_id', params, config)
export const editBooking = (params, config = {}) => uni.$u.http.post('/app/booking/edit', params, config)
export const getBookingsByGroupId = (params, config = {}) => uni.$u.http.post('/app/booking/get_bookings_by_groupId', params, config)
export const cancelWaitlistBooking = (params, config = {}) => uni.$u.http.post('/app/booking/cancel_waitlist', params, config)
export const cancelApproval = (params, config = {}) => uni.$u.http.post('/app/approval/cancel_approval', params, config)
export const approveWaitlistBooking = (params, config = {}) => uni.$u.http.post('/app/booking/approve_waitlist', params, config)
export const changeMiscCharge = (params, config = {}) => uni.$u.http.post('/app/booking/change_misc_charge', params, config)
+6
View File
@@ -0,0 +1,6 @@
export const writeDebugLog = (params, config = {}) => uni.$u.http.post('/system/write_log', params, config)
export const getSettingByKey = (params, config = {}) => uni.$u.http.post('/system/sys_setting/get', params, config)
export const getSettings = (params, config = {}) => uni.$u.http.post('/system/sys_setting/get_list', params, config)
export const verifyToken = (params, config = {}) => uni.$u.http.post('/app/me', params, config)
export const refreshToken = (params, config = {}) => uni.$u.http.post('/app/refresh_token?isRenewRefreshToken=false', params, config)
export const logout = (params, config = {}) => uni.$u.http.post('/app/logout', params, config)
+12
View File
@@ -0,0 +1,12 @@
export const getProperties = (params, config = {}) => uni.$u.http.post('/app/config/property_list', params, config)
export const getBookingTypes = (params, config = {}) => uni.$u.http.post('/app/config/booking_type_list', params, config)
export const getRooms = (params, config = {}) => uni.$u.http.post('/app/config/room_list', params, config)
export const getRoomTypes = (params, config = {}) => uni.$u.http.post('/app/config/room_type_list', params, config)
export const getSpecials = (params, config = {}) => uni.$u.http.post('/app/config/special_list', params, config)
export const getBedTypes = (params, config = {}) => uni.$u.http.post('/app/config/bed_type_list', params, config)
export const getCriterias = (params, config = {}) => uni.$u.http.post('/app/config/criteria_list', params, config)
export const getSetting = (params, config = {}) => uni.$u.http.post('/app/config/setting_list', params, config)
export const getAvailableRoom = (params, config = {}) => uni.$u.http.post('/app/config/available_room_list', params, config)
export const getExtendBooking = (params, config = {}) => uni.$u.http.post('/app/config/is_extend_booking', params, config)
export const getWaitlistBooking = (params, config = {}) => uni.$u.http.post('/app/config/get_waitlist_booking', params, config)
export const getCfgSettingByKey = (params, config = {}) => uni.$u.http.post('/web/setting/get_setting_by_key', params, config)
+3
View File
@@ -0,0 +1,3 @@
export const playerLookup = (params, config = {}) => uni.$u.http.post('/app/mgm/player_lookup', params, config)
export const checkTPD = (params, config = {}) => uni.$u.http.post('/app/mgm/check_tpd_by_playerId_room_dates', params, config)
export const checkSecondTPD = (params, config = {}) => uni.$u.http.post('/app/mgm/check_second_tpd_by_playerId_room_dates', params, config)
+9
View File
@@ -0,0 +1,9 @@
export const saveNotification = (params, config = {}) => uni.$u.http.post('/notification/saveNotification', params, config)
export const getNotificationByUserId = (params, config = {}) =>
uni.$u.http.get('/notification/get_notification_by_user_id', { params, ...config })
export const changeNotification = (params, config = {}) => uni.$u.http.post('/notification/change_status', params, config)
export const readAllNotification = (params, config = {}) => uni.$u.http.post('/notification/read_all', params, config)
export const countNotification = (params, config = {}) =>
uni.$u.http.get('/notification/count_notification_by_user_id', { params, ...config })
export const saveDeviceToken = (params, config = {}) => uni.$u.http.post('/deviceToken/save_device_token', params, config)
export const updateDeviceToken = (params, config = {}) => uni.$u.http.post('/deviceToken/update_device_token', params, config)
+4
View File
@@ -0,0 +1,4 @@
export const mockUserSSOLogin = (params, config = {}) => uni.$u.http.post('/app/sso/mock_user_sso_login', params, config)
export const getSSOTokenByCode = (params, config = {}) => uni.$u.http.post('/app/sso/get_sso_token_by_code', params, config)
export const userSSOlogin = (params, config = {}) => uni.$u.http.post('/app/sso/user_sso_login', params, config)
export const userOpenIdlogin = (params, config = {}) => uni.$u.http.post('/app/sso/loginidp', params, config)
+8
View File
@@ -0,0 +1,8 @@
export const getTodoDashboard = (params, config = {}) => uni.$u.http.post('/app/todo/get_dashboard_data', params, config)
export const getTodoDetail = (params, config = {}) => uni.$u.http.post('/app/todo/get_todolist_details', params, config)
export const getTodoList = (params, config = {}) => uni.$u.http.post('/app/todo/get_todolist', params, config)
export const submitETA = (params, config = {}) => uni.$u.http.post('/app/todo/submit_ETA', params, config)
export const cancelBooking = (params, config = {}) => uni.$u.http.post('/app/todo/cancel_booking', params, config)
export const changeDate = (params, config = {}) => uni.$u.http.post('/app/todo/change_date', params, config)
export const userConfirm = (params, config = {}) => uni.$u.http.post('/app/log_confirm/save_confirm_log', params, config)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+195
View File
@@ -0,0 +1,195 @@
<template>
<view>
<view class="hz-page">
<u-navbar
:safeAreaInsetTop="true"
:placeholder="true"
:title="title"
:fixed="true"
:autoBack="true"
leftIconColor="#000000"
titleStyle="font-weight:bold;"
>
<view
style="margin-top:2px;margin-right:3px;"
slot="right"
>
<view style="border:1rpx solid #ccc;border-radius: 14px;padding:4px 12px;" class="hz-flex-row hz-flex-vertical-mid">
<image @click="navTo('/pages/findPlayer/findPlayer',1,false)" src="../../static/images/ico_find_player.png" class="hz-nav-btn"></image>
<view style="height:20px;border-left:1px solid #ccc;margin-left:8px;margin-right:8px;"></view>
<image @click="navTo('/booking/bookingRecord/bookingRecord',0,false)" src="../../static/images/ico_list.png" class="hz-nav-btn"></image>
</view>
</view>
</u-navbar>
<view class="hz-spacing hz-bg-white" style="margin-top:8px;">
<view class="hz-card-profile hz-mr-b-30">
<view class="hz-flex-row">
<view style="width:60%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.playerId")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{ playerData.playerId }}</view>
</view>
<view style="width:40%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.tier")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{ playerData.tierName }}</view>
</view>
</view>
<view class="hz-flex-row hz-mr-t-30">
<view style="width:100%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.name")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{playerData.salutation + ". " + playerData.name }}</view>
</view>
</view>
</view>
<view v-if="!showEmpty">
<view v-for="(booking,index) in bookingList" :key="index" :class="(booking.lastOperaStatus==='DUE_OUT' || booking.lastOperaStatus==='CHECKED_IN') && booking.confirmationNo!=null? 'hz-card-extend':'hz-card-booking'" class="hz-pd-30 hz-font-bold hz-font-sm" style="margin-top:20rpx;align-items: center;">
<view @click="navToDetail(booking)" class="hz-flex-row">
<view style="width:60%;">
<view>{{$t("common.property")}}: {{ booking.propertyName }}</view>
</view>
<view style="width:40%;">
<view>{{$t("common.roomType")}}: {{ booking.roomTypeCode }}</view>
</view>
</view>
<view @click="navToDetail(booking)" class="hz-flex-row" style="margin-top:8px;">
<view style="width:60%;">
<view>{{$t("common.checkInDate")}}: {{ dateFormat(booking.checkinDate) }}</view>
</view>
<view style="width:40%;">
<view>{{$t("common.confirmationNo")}}: {{ getConfirmationNo(booking) }}</view>
</view>
</view>
<view class="hz-flex-row" style="margin-top:8px;">
<view @click="navToDetail(booking)" style="width:60%;">
<view>{{$t("common.checkOutDate")}}: {{ dateFormat(booking.checkoutDate) }}</view>
</view>
<view class="hz-flex-row" style="width:40%;justify-content: flex-end;">
<view @click="navToDetail(booking)" v-if="(booking.sharer===null || booking.sharer==='[]') && ((booking.lastOperaStatus==='DUE_OUT' || booking.lastOperaStatus==='CHECKED_IN') && booking.confirmationNo!=null)" class="hz-btn-extend">{{$t("bookingRecord.extend")}}</view>
<view @click="navTo('/booking/bookingGroup/bookingGroup?groupId='+booking.groupId,0,false)" v-if="booking.groupId!==undefined && booking.groupId!==''" class="hz-btn-group" style="margin-left:8px;">{{$t("bookingRecord.group")}}</view>
<view v-if="booking.sharer!==null && booking.sharer!=='[]'" class="hz-btn-sharer" style="margin-left:8px;">{{$t("bookingRecord.sharer")}}</view>
</view>
</view>
</view>
<view :style="'height:'+footFuncHei+'rpx;'"></view>
</view>
<u-empty
v-if="showEmpty"
mode="search"
:text="dataNotFoundStr"
>
</u-empty>
</view>
</view>
</view>
</template>
<script>
import dayjs from '../../uni_modules/uview-ui/libs/util/dayjs.js';
import {getBookingsByGroupId} from '../../api/bookingApi.js';
export default {
data() {
return {
//数据变量
playerData:null,
bookingList:[],
userData:null,
groupId:'',
// 界面变量
dataNotFoundStr:this.$t("common.dataNotFound"),
showEmpty:false,
title:'',
footFuncHei:100,
}
},
onLoad(opt) {
// 初始化界面
this.initUI();
this.playerData = uni.getStorageSync("playerData");
this.userData = uni.getStorageSync("userData");
this.groupId = opt.groupId;
this.getBookings();
},
onShow() {
},
methods: {
// 數據方法
async getBookings(){
uni.showLoading({
title: this.$t("common.loading")
});
try{
let params = {};
params.groupId = this.groupId;
const res = await getBookingsByGroupId(params);
if(res.success == true){
this.bookingList = [];
this.bookingList = res.data;
this.showEmpty = false;
}else{
// 出错
this.showEmpty = true;
}
}catch(e){
console.error(e);
this.showEmpty = true;
}finally{
uni.hideLoading();
}
},
//下拉刷新
onPullDownRefresh() {
this.pullDownRefresh();
},
pullDownRefresh(){
try{
this.getBookings();
}finally{
uni.stopPullDownRefresh();
}
},
// 界面方法
navToDetail(booking){
this.navTo('/booking/bookingDetail/bookingDetail?id='+booking.id+"&conf="+booking.confirmationNo+"&from=list",0,false)
},
initUI() {
this.deviceData = uni.getStorageSync("deviceData");
this.title = this.$t("bookingRecord.title");
// 判斷iphone下方安全區域
const area = this.deviceData.saveArea;
if(area){
this.footFuncHei = 160;
}
},
},
computed:{
getConfirmationNo(){
return function (booking) {
if(booking!==undefined && booking!==null){
if(booking.confirmationNo!==undefined && booking.confirmationNo!==null && booking.confirmationNo!=='null' && booking.confirmationNo!==''){
return booking.confirmationNo;
}
else
{
return 'N/A';
}
}else{
return 'N/A';
}
}
},
dateFormat() {
return function (date) {
if (date != undefined) {
return dayjs(date).format("DD/MM/YY");
}
}
},
}
}
</script>
<style lang="scss" scoped>
</style>
+579
View File
@@ -0,0 +1,579 @@
<template>
<view>
<view class="hz-page">
<u-navbar
:safeAreaInsetTop="true"
:placeholder="true"
:title="title"
:fixed="true"
:autoBack="false"
leftIconColor="#000000"
titleStyle="font-weight:bold;"
@leftClick="back()"
>
<view
style="margin-top:2px;margin-right:3px;"
slot="right"
>
<view style="border:1rpx solid #ccc;border-radius: 14px;padding:4px 12px;" class="hz-flex-row hz-flex-vertical-mid">
<image @click="navTo('/pages/findPlayer/findPlayer',1,false)" src="../../static/images/ico_find_player.png" class="hz-nav-btn"></image>
<view style="height:20px;border-left:1px solid #ccc;margin-left:8px;margin-right:8px;"></view>
<image @click="getDataByPage" src="../../static/images/ico_list.png" class="hz-nav-btn"></image>
</view>
</view>
</u-navbar>
<view class="hz-spacing hz-bg-white" style="margin-top:8px;">
<view class="hz-card-profile hz-mr-b-30">
<view class="hz-flex-row">
<view style="width:60%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.playerId")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{ playerData.playerId }}</view>
</view>
<view style="width:40%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.tier")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{ playerData.tierName }}</view>
</view>
</view>
<view class="hz-flex-row hz-mr-t-30">
<view style="width:100%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.name")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{playerData.salutation + " " + playerData.name }}</view>
</view>
</view>
</view>
<view v-if="!showEmpty">
<!-- 'hz-card-extend' disable extend -->
<view @click="navToDetail(booking)" v-for="(booking,index) in bookingList" :key="index"
:class="getRecordColor(booking)" class="hz-pd-30 hz-font-bold hz-font-sm" style="margin-top:20rpx;align-items: center;">
<view class="hz-flex-row">
<view>
<view class="hz-font-md">{{$t("common.confirmationNo")}}: {{ getConfirmationNo(booking)}}</view>
</view>
<view style="margin-left:auto">
<view class="hz-font-md" :class="getStatusTextColor(booking)">{{getStatusText(booking)}}</view>
</view>
</view>
<view class="hz-flex-row" style="margin-top:6px;">
<view style="width:55%;">
<view class="hz-font-md">{{$t("common.checkInDate")}}: {{ booking.checkinDate }}</view>
</view>
<view style="width:50%;">
<view style="text-align: right;" class="hz-font-md">{{ booking.propertyName }}</view>
</view>
</view>
<view class="hz-flex-row" style="margin-top:6px;">
<view style="width:55%;">
<view class="hz-font-md">{{$t("common.checkOutDate")}}: {{ booking.checkoutDate }}</view>
</view>
<!-- enable sharer and extend 2024-09-27 -->
<view class="hz-flex-row" style="width:50%;text-align: right;justify-content: flex-end;" v-if="userData.canNewBooking&&booking.propertyCategory!='OTHER'">
<view v-if="(booking.sharer!==null && booking.sharer!=='[]')||booking.isShare" class="hz-btn-sharer hz-font-min" style="width:40%;height:14px;line-height:14px;margin-right: 3px;">{{$t("bookingRecord.sharer").toUpperCase()}}</view>
<!-- <view @click="navToDetail(booking)" v-if="((booking.lastOperaStatus==='DUE_OUT' || booking.lastOperaStatus==='CHECKED_IN') && booking.confirmationNo!=null && (booking.approveStatus!='W'&&booking.approveStatus!='PN'))" class="hz-btn-extend hz-font-min" style="width:40%;height:14px;line-height:14px;">{{$t("bookingRecord.extend").toUpperCase()}}</view> -->
<!-- <view @click="navTo('/booking/bookingGroup/bookingGroup?groupId='+booking.groupId,0,false)" v-if="booking.groupId!==undefined && booking.groupId!==null && booking.groupId!==''" class="hz-btn-group" style="margin-left:8px;">{{$t("bookingRecord.group")}}</view> -->
</view>
</view>
<view class="hz-flex-row" style="margin-top:6px;">
<view v-show="booking.eta!==null && booking.eta!=='00:00:00'" class="hz-font-md">{{$t("common.etaTime")}}: {{formatEtaToHHmm(booking.eta)}}</view>
<span v-show="booking.eta!==null && booking.eta!=='00:00:00' && booking.miscCharge!==null" class="hz-font-md" style="padding:0 6px;">|</span>
<view v-show="booking.miscCharge!==null" class="hz-font-md">{{$t("common.misCharge")}}: {{formatWithThousands(booking.miscCharge)}}</view>
</view>
</view>
<!-- <u-loadmore :status="showLoadMore" :loadmoreText="loadMoreStr" :nomoreText="nomoreStr" :fontSize="14" color="#ccc" :line="true" /> -->
</view>
<u-empty
v-if="showEmpty"
mode="search"
:text="dataNotFoundStr"
>
</u-empty>
</view>
<u-tabbar
:fixed="true"
:placeholder="true"
:safeAreaInsetBottom="true"
customStyle="z-index:100;height:58px;"
v-if="userData.canNewBooking"
>
<view class="book hz-flex-row hz-spacing">
<view class="hz-btn hz-font-color-white hz-font-lg hz-font-bold hz-text-center" @click="navToNewBooking()">
{{$t("bookingRecord.newsBooking")}}
</view>
</view>
</u-tabbar>
<u-modal :content="msgStr" :show="showMsg" :confirmText="yesText" :showCancelButton="false" closeOnClickOverlay @confirm="showMsg=false" confirmColor="#C39A4B" @close="showMsg=false"></u-modal>
</view>
</view>
</template>
<script>
import {playerLookup} from '../../api/mgmApi.js'
import {mapOperaStatus,mapApproveStatus} from '../../common/mapping.js'
import {getBookingsMock,getBookings} from '../../api/bookingApi.js';
import dayjs from '../../uni_modules/uview-ui/libs/util/dayjs.js';
export default {
data() {
return {
//数据变量
playerData:null,
userData:null,
bookingList:[],
dataNotFoundStr:this.$t("common.dataNotFound"),
// 界面变量
from:'',
showEmpty:false,
title:'',
footFuncHei:100,
currentIndex:0,
showMsg:false,
msgStr:this.$t("bookingRecord.operaProfile"),
yesText:this.$t("common.ok"),
currentTask:null,
getDataByPageRequestId:0,
}
},
onLoad(opt) {
// 初始化界面
this.initUI();
this.playerData = uni.getStorageSync("playerData");
this.userData = uni.getStorageSync("userData");
if(opt.from!==undefined && opt.from!='') this.from = opt.from;
// this.getDataByPage();
},
onShow() {
this.$i18n.locale = uni.getLocale();
// 检查是否登录
this.isLogin();
// 拿localstorage中的playerData
this.getDataByPage();
},
// 下拉刷新(页面生命周期,需与 onLoad/onShow 同级)
onPullDownRefresh() {
this.pullDownRefresh();
},
methods: {
// 數據方法
async getDataByPage(){
if(this.userData.canViewBooking==false) return;
if(this.currentTask){
try{
this.currentTask.abort();
}catch(err){
}
}
const requestId = ++this.getDataByPageRequestId;
let params = {};
uni.showLoading({
title: this.$t("common.loading")
});
try{
if(this.playerData.nameIds.length==0){
await this.getProfileByPlayerId(requestId)
}else{
params.member = this.playerData
params.userId = this.userData.userId;
const res = await getBookings(params, {
getTask: (task, options) => {
this.currentTask = task;
}
});
if(requestId !== this.getDataByPageRequestId) return;
this.currentTask = null;
this.bookingList = [];
if(res.length>0){
if(res!==undefined && res!==null){
this.bookingList = res;
}
}else{
}
}
}catch(e){
if(e.errMsg!==undefined && e.errMsg.includes("abort")){
return;
}
// console.log(e);
// write log
uni.$u.toast(e.errMsg,5000);
await this.writeLog(this.userData.userId,"save_booking","","[APP][bookingDetail.vue][getDataByPage][Catch Exception]"+e.errMsg,"[RequestData]" +JSON.stringify(params),"",1,false);
}finally{
if(requestId === this.getDataByPageRequestId){
this.currentTask = null;
uni.hideLoading();
}
}
},
pullDownRefresh(){
try{
this.getDataByPage('refresh');
}finally{
uni.stopPullDownRefresh();
}
},
// 界面方法
back(){
if(this.from==='booking'){
this.navTo("/pages/findPlayer/findPlayer",1,false);
}else{
this.navBack();
}
},
navToDetail(booking){
this.navTo('/booking/bookingDetail/bookingDetail?id='+booking.id+"&conf="+booking.confirmationNo+"&from=list",0,false)
},
// ETA 统一显示 HH:mm(兼容 HH:mm:ss / HH:mm)
formatEtaToHHmm(eta) {
if (eta === null || eta === undefined || eta === '') return '';
const str = String(eta).trim();
const m = str.match(/^(\d{1,2}):(\d{2})(?::\d{2})?$/);
if (m) {
const hh = m[1].padStart(2, '0');
return `${hh}:${m[2]}`;
}
// 兜底:如果有冒号,取前两段
const parts = str.split(':');
if (parts.length >= 2) {
return `${parts[0].padStart(2, '0')}:${parts[1]}`;
}
return str;
},
formatWithThousands(value) {
if (value === null || value === undefined || value === '') return '-';
const str = String(value).trim();
if (/^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test(str)) return str;
const normalized = str.replace(/,/g, '');
if (/^-?\d+(\.\d+)?$/.test(normalized)) {
const n = Number(normalized);
return n.toLocaleString('en-US');
}
return value;
},
initUI() {
this.deviceData = uni.getStorageSync("deviceData");
this.title = this.$t("bookingRecord.title");
},
navToNewBooking(){
this.getDataByPage();
uni.showLoading({
title: this.$t("common.loading")
});
// remove no opera restrict
// if(this.playerData.nameIds.length==0){
// this.showMsg = true;
// }else{
// this.navTo('/booking/newBooking/newBooking',0,false)
// }
this.navTo('/booking/newBooking/newBooking',0,false)
uni.hideLoading();
},
async getProfileByPlayerId(requestId){
try{
let params = {playerId:this.playerData.playerId,userId:this.userData.userId};
const res = await playerLookup(params, {
getTask: (task, options) => {
this.currentTask = task;
}
});
if(requestId !== this.getDataByPageRequestId) return;
if(res.success == true){
var player = res.data;
if(player !== null){
if(player.codedFlag==1){
uni.setStorageSync("playerData",player);
this.playerData = uni.getStorageSync("playerData");
let params = {};
params.member = player
params.userId = this.userData.userId;
const res = await getBookings(params, {
getTask: (task, options) => {
this.currentTask = task;
}
});
if(requestId !== this.getDataByPageRequestId) return;
this.currentTask = null;
this.bookingList = [];
if(res.length>0){
if(res!==undefined && res!==null){
this.bookingList = res;
}
}else{
}
}
}
}
}catch(e){
if(e.errMsg!==undefined && e.errMsg.includes("abort")){
return;
}
console.error(e);
var request = e.config!=undefined?JSON.stringify(e.config):"";
var response = e.data!=undefined?JSON.stringify(e.data):"";
await this.writeLog(this.userData.userId,"find_player","","[APP][findPlayer.vue][getProfileByPlayerId][Catch Exception]"+e.errMsg,request,response,1,false);
}finally{
}
},
},
computed:{
getConfirmationNo(){
return function (booking) {
if(booking!==undefined && booking!==null){
if(booking.confirmationNo!==undefined && booking.confirmationNo!==null &&
booking.confirmationNo!=='null' && booking.confirmationNo!=='' && booking.approveStatus!='W'){
return booking.confirmationNo;
}
else
{
return 'N/A';
}
}else{
return 'N/A';
}
}
},
dateFormat() {
return function (date) {
if (date != undefined) {
return dayjs(date).format("DD/MM/YY");
}
}
},
getStatusColor(){
return function (booking) {
let operaStatus = null;
if(booking==null){
return '';
}
if(booking.lastOperaStatus!=null){
operaStatus = booking.lastOperaStatus;
}
let approveStatus = null;
if(booking.approveStatus!=null){
approveStatus = booking.approveStatus;
}
// Opera和Approve Status都不为空的情况
if((operaStatus!=null && operaStatus!=undefined) || (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'){
return 'hz-status-pending';
}else if(approveStatus.toUpperCase()==='N'){
if(operaStatus!==null && operaStatus!==undefined && operaStatus!=='' && operaStatus!=='null'){
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-reserved';
}
else
{
return '';
}
}
}else if(approveStatus.toUpperCase()==='W' ||approveStatus.toUpperCase()==='WA'){
return 'hz-status-waitlist';
}
else
{
if(operaStatus==null) return '';
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-reserved';
}
else
{
return '';
}
}
}
// Opera status为空,Approve Status不为空的情况
else if((operaStatus==null || operaStatus==undefined) && (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'){
return 'hz-status-font-pending';
}else if(approveStatus.toUpperCase()==='W' || approveStatus.toUpperCase()==='WA'){
return 'hz-status-font-waitlist';
}else if(approveStatus.toUpperCase()==='AP'){
console.log(111);
return 'hz-status-font-approval'
}else{
return '';
}
}
}
},
getStatusTextColor(){
return function (booking) {
let operaStatus = null;
if(booking==null){
return '';
}
if(booking.lastOperaStatus!=null){
operaStatus = booking.lastOperaStatus;
}
let approveStatus = null;
if(booking.approveStatus!=null){
approveStatus = booking.approveStatus;
}
// Opera和Approve Status都不为空的情况
if((operaStatus!=null && operaStatus!=undefined) || (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'||approveStatus.toUpperCase()==='F'){
return 'hz-status-font-pending';
}else if(approveStatus.toUpperCase()==='N' || approveStatus.toUpperCase()==="FC"){
if(operaStatus!==null && operaStatus!==undefined && operaStatus!=='' && operaStatus!=='null'){
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-font-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-font-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-font-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-font-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-font-reserved';
}
else if(operaStatus.toUpperCase()==='PENDING CANCEL'){
return 'hz-status-font-cancel';
}
else
{
return '';
}
}
}else if(approveStatus.toUpperCase()==='W'|| approveStatus.toUpperCase()==='WA'){
return 'hz-status-font-waitlist';
}else if(approveStatus.toUpperCase()==='AP'){
return 'hz-status-font-approval';
}
else
{
if(operaStatus==null) return '';
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-font-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-font-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-font-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-font-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-font-reserved';
}
else
{
return '';
}
}
}
// Opera status为空,Approve Status不为空的情况
else if((operaStatus==null || operaStatus==undefined) && (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'||approveStatus.toUpperCase()==='F'){
return 'hz-status-font-pending';
}else if(approveStatus.toUpperCase()==='W' || approveStatus.toUpperCase()==='WA'){
return 'hz-status-font-waitlist';
}
else{
return '';
}
}
}
},
getStatusText(){
return function (booking) {
let operaStatus = null;
if(booking==null){
return;
}
if(booking.lastOperaStatus!=null){
operaStatus = booking.lastOperaStatus;
}
let approveStatus = null;
if(booking.approveStatus!=null){
approveStatus = booking.approveStatus;
}
if((operaStatus!=null && operaStatus!=undefined) || (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN' || approveStatus.toUpperCase()==='W' || approveStatus.toUpperCase()==='WA'
|| approveStatus.toUpperCase()==='F' || approveStatus.toUpperCase()==='AP'){
if(approveStatus!==null && approveStatus!==undefined && approveStatus!=='' && approveStatus!=='null'){
if(approveStatus.toUpperCase()==='F'&&booking.tryTime<5){
return "PENDING";
}else{
return mapApproveStatus(approveStatus.toUpperCase());
}
}
}else if( approveStatus.toUpperCase()==='N' || approveStatus.toUpperCase()==='FC'){
if(operaStatus!==null && operaStatus!==undefined && operaStatus!=='' && operaStatus!=='null')
return mapOperaStatus(operaStatus.toUpperCase());
}
}
else if((operaStatus==null || operaStatus==undefined) && (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='F'&&booking.tryTime<5){
return "PENDING";
}else{
return mapApproveStatus(approveStatus.toUpperCase());
}
}
}
},
getRecordColor(){
return function (booking) {
if(booking.approveStatus==='W'|| booking.approveStatus==='WA'){
return 'hz-card-waitlist'
}else if((booking.lastOperaStatus==='DUE_OUT' || booking.lastOperaStatus==='CHECKED_IN') && booking.confirmationNo!=null && (booking.sharer==null || booking.sharer==='[]' || booking.sharer==='')){
return 'hz-card-booking'
}else if(booking.approveStatus==='AP'){
return 'hz-card-approval'
}else{
return 'hz-card-booking'
}
}
},
getETA(){
return function(ETA){
let returnStr = [];
if(ETA !== null && ETA !== undefined){
returnStr = ETA.split(":");
return returnStr[0] + ":" +returnStr[1];
}
return null;
}
}
}
}
</script>
<style lang="scss" scoped>
</style>
+389
View File
@@ -0,0 +1,389 @@
<template>
<view>
<view class="hz-page">
<u-navbar
:safeAreaInsetTop="true"
:placeholder="true"
:title="title"
:fixed="true"
:autoBack="true"
leftIconColor="#000000"
titleStyle="font-weight:bold;"
>
<view
style="margin-top:2px;margin-right:3px;"
slot="right"
>
<view style="border:1rpx solid #ccc;border-radius: 14px;padding:4px 12px;" class="hz-flex-row hz-flex-vertical-mid">
<image @click="navTo('/pages/findPlayer/findPlayer',1,false)" src="../../static/images/ico_find_player.png" class="hz-nav-btn"></image>
<view style="height:20px;border-left:1px solid #ccc;margin-left:8px;margin-right:8px;"></view>
<image @click="navTo('/booking/bookingRecord/bookingRecord',0,false)" src="../../static/images/ico_list.png" class="hz-nav-btn"></image>
</view>
</view>
</u-navbar>
<view v-for="(item,index) in bookingData.dateList" :key="'date'+index" class="hz-spacing hz-bg-white" style="margin-top:10px;">
<view class="hz-pd-30 hz-font-bold hz-font-sm hz-card-extend hz-flex-row" style="margin-top:20rpx;align-items: center;">
<view class="hz-flex-row" style="align-items: center;width:90%;">
<image src="../../static/images/ico_calendar.png" style="width:16px;height:16px;"></image>
<span class="hz-font-sm hz-font-bolder" style="margin-left:4px;">{{dateFormat(item.date[0])}} - {{dateFormat(item.date[item.date.length-1])}}</span>
</view>
<view @click="delDate(index)" class="hz-flex-row" style="width:10%;justify-content: flex-end;">
<u-icon name="trash" size="20" color="#c04b41"></u-icon>
</view>
</view>
</view>
<u-tabbar
:fixed="true"
:placeholder="true"
:safeAreaInsetBottom="true"
customStyle="z-index:100;height:58px;"
>
<view class="hz-btn-leftRight hz-flex-row hz-spacing">
<view @click="popupCalendar()" class="hz-btn-left hz-bg-light hz-font-lg hz-font-bold hz-font-color-primary" >{{$t("multipleDate.addDate")}}</view>
<view @click="navToConfirm()" class="hz-btn-right hz-bg-primary hz-font-lg hz-font-bold hz-font-color-white" >{{$t("common.confirm").toUpperCase()}}</view>
</view>
</u-tabbar>
</view>
<u-modal :content="msgStr" :show="showMsg" :cancelText="cancelText" :confirmText="yesText" showCancelButton closeOnClickOverlay @confirm="confirmDel" confirmColor="#C39A4B" @cancel="cancelMsg" @close="cancelMsg"></u-modal>
<u-calendar
closeOnClickOverlay
:confirmText="confirmText"
:confirmDisabledText="confirmText"
color="#C39A4B"
title=""
:startText="inText"
:endText="outText"
:show="showCalendar"
:defaultDate="bookingData.dateList.at(-1)!=null?[bookingData.dateList.at(-1).date.at(-1)]:[]"
:formatter="formatter"
mode="range"
:monthNum="monthNum"
:maxRange="maxRange"
:footerInfo="footerInfo"
@close="cancelDate"
@confirm="confirmDate"
@rangeSelected="rangeSelected">
</u-calendar>
</view>
</template>
<script>
import dayjs from '../../uni_modules/uview-ui/libs/util/dayjs.js';
import {getSetting,getCriterias,getAvailableRoom} from '../../api/configApi.js';
export default {
data() {
return {
//数据变量
playerData:null,
userData:null,
bookingData:null,
criteriaList:[],
maxDate:'',
defaultDate:[],
// 界面变量
title:'',
msgStr:this.$t("common.removeConfirm"),
cancelText:this.$t("common.cancel"),
confirmText:this.$t("common.confirm").toUpperCase(),
inText:this.$t("common.in"),
outText:this.$t("common.out"),
yesText:this.$t("common.yes"),
showCalendar:false,
showMsg:false,
footFuncHei:100,
footerInfo:"",
bookNum:1,
maxRange:0,
monthNum:0,
}
},
onLoad() {
// 初始化界面
this.initUI();
this.playerData = uni.getStorageSync("playerData");
this.userData = uni.getStorageSync("userData");
this.bookingData = uni.getStorageSync("bookingData");
},
onShow() {
// 检查是否登录
// this.isLogin();
this.getSetting();
},
methods: {
// 數據方法
async buildCalendar(){
uni.showLoading({
title: this.$t("common.loading")
});
try{
let params = {
roomId:this.bookingData.roomId,
propertyId:this.bookingData.propertyId,
blockId:this.bookingData.blockId,
coded:this.playerData.coded,
userId:this.userData.userId,
playerId:this.playerData.playerId,
};
const res = await getCriterias(params);
if(res.success === true){
this.criteriaList = [];
if(res.data!==undefined && res.data!==null){
this.criteriaList = res.data;
}
}else{
}
}catch(e){
}finally{
uni.hideLoading();
}
},
// 界面方法
navToConfirm(){
// 數據檢查,臨時保存,跳轉到確認頁
if(this.bookingData.dateList.length==0){
uni.$u.toast(this.$t("multipleDate.pleaseAddDate"));
return;
}
this.navTo("/booking/bookingConfirm/bookingConfirm",0,false);
},
async popupCalendar(){
if(this.bookingData.dateList.length==this.bookNum){
uni.$u.toast(this.$t("multipleDate.reachMaxBookNum"));
return;
}
await this.buildCalendar();
this.showCalendar = true;
},
confirmDate(e){
let checkDate =JSON.parse(JSON.stringify(e));
checkDate.pop();
if(!this.checkDate(checkDate)) return false;
let objDate ={
date:e,
status:null,
checked:false,
remark:'',
numOfNight:dayjs(e[e.length-1]).diff(dayjs(e[0]),'day'),
numOfRoom:1,
};
// 把對應的criteria也放到booking裡面後面用
for(let i=0;i<e.length;i++){
const date = e[i];
const criterias = this.criteriaList;
if(criterias[date]!==undefined && criterias[date]!=null)
this.bookingData.criteriaList.push(criterias[date]);
}
this.bookingData.dateList.push(objDate);
uni.setStorageSync("bookingData",this.bookingData);
this.showCalendar = false;
},
confirmDel(){
// 從dateList中刪除
if(this.bookingData.dateList!=undefined && this.bookingData.dateList!=null){
for(let i=0;i<this.bookingData.dateList[this.deleteIndex].date.length;i++){
const date1 = this.bookingData.dateList[this.deleteIndex].date[i];
if(this.bookingData.criteriaList!=null && this.bookingData.criteriaList.length>0){
for(let a=0;a<this.bookingData.criteriaList.length;a++){
let date2 = this.bookingData.criteriaList[a].bookDate;
if(date1 == date2){
this.bookingData.criteriaList.splice(a,1);
break;
}
}
}
}
this.bookingData.dateList.splice(this.deleteIndex,1);
uni.setStorageSync("bookingData",this.bookingData);
}
this.showMsg = false;
},
delDate(index){
this.showMsg = true;
this.deleteIndex = index;
},
cancelMsg(){
this.showMsg = false;
},
cancelDate(){
this.showCalendar = false;
},
formatter(day) {
if(this.criteriaList!=null){
let cdate = dayjs(day.date).format("YYYY-MM-DD");
for(let i=0;i<this.bookingData.dateList.length;i++){
let dates = this.bookingData.dateList[i].date;
for(let j=0;j<dates.length;j++){
let date = dates[j];
if(cdate == date){
day.picked = true
if(j!=dates.length-1) // 可以连接上日期的处理
day.disabled = true
break;
}
}
}
if(this.criteriaList[cdate]!=undefined){
let criteria =this.criteriaList[cdate];
if(criteria.isWaitlist==1){
day.bottomInfo = 'Waitlist'
day.dot = true
}
if(criteria.protection==1){
day.bottomInfo = 'Protect'
day.dot = true
}
if(criteria.available==0){
day.bottomInfo = 'Full'
day.dot = true
}
}else{
day.bottomInfo = 'Full'
day.dot = true
}
}
return day
},
initUI() {
this.deviceData = uni.getStorageSync("deviceData");
this.title = this.$t("multipleDate.title");
// 判斷iphone下方安全區域
const area = this.deviceData.saveArea;
if(area){
this.footFuncHei = 160;
}
},
async getSetting(){
uni.showLoading({
title: this.$t("common.loading")
});
var that = this;
try{
let params = {};
const res = await getSetting(params);
if(res!=null && res.success==true){
for(let i of res.data){
if(i.keys=="MAX_BOOKING_STAY_DAYS"){
let stay = i.keyValues;
that.maxRange = stay;
}else if(i.keys=="NUM_OF_MULTIPLE_DATE_RANGE"){
that.bookNum = i.keyValues;
}else if(i.keys=="MAX_ADVANCE_BOOKING_DAYS"){
var monthNum = i.keyValues/30;
that.monthNum = Math.ceil(monthNum)+1;
let mDate = dayjs().add(i.keyValues,'day').format("YYYY-MM-DD");
that.maxDate = mDate
}
}
}
else
{
// write log
}
}catch(e){
// write log
}finally{
uni.hideLoading();
}
},
async rangeSelected(e){
var isWaitlist = false;
for(let d of e){
if(this.criteriaList[d]!=undefined){
if(this.criteriaList[d].isWaitlist==1)isWaitlist = true;
}
}
if(isWaitlist){
try{
let params = {
roomId:this.modelBooking.roomId,
propertyId:this.modelBooking.propertyId,
blockId:this.modelBooking.blockId,
selectDate: [e[0],e[e.length-1]],
};
const res = await getAvailableRoom(params);
if(res.success === true){
if(res.data.length>0) {
this.footerInfo = "Available Room:"+res.data.join(',');
}else{
this.footerInfo = "";
}
}
}catch(e){
}
}else{
this.footerInfo = "";
}
},
checkDate(date){
var protectList = [];
var fullList = [];
for(let d of date){
if(this.criteriaList[d]!=undefined){
if(this.criteriaList[d].available==0) fullList.push(d);
if(this.criteriaList[d].protection==1) protectList.push(d);
}else{
fullList.push(d);
}
}
if(fullList.length>0){
let msg = this.$t("newBooking.appFull");
msg += " "+fullList.join(',')
uni.$u.toast(msg,3000);
return false;
}
if(protectList.length>0){
let msg = this.$t("newBooking.protectionPeriod");
msg += " "+protectList.join(',')
uni.$u.toast(msg,3000);
return false;
}
return true;
}
},
computed:{
dateFormat() {
return function (date) {
if (date != undefined) {
let weekNum = dayjs(date).day();
let week = '';
switch(weekNum){
case 1:
week='Mon'
break;
case 2:
week='Tue';
break;
case 3:
week='Wed';
break;
case 4:
week='Thu';
break;
case 5:
week='Fri';
break;
case 6:
week='Sat';
break;
case 0:
week='Sun';
break;
}
return week + ', ' + dayjs(date).format("MMM D/YYYY");
}
}
},
}
}
</script>
<style lang="scss" scoped>
</style>
File diff suppressed because it is too large Load Diff
+655
View File
@@ -0,0 +1,655 @@
<template>
<view>
<view class="hz-page">
<u-navbar
:safeAreaInsetTop="true"
:placeholder="true"
:title="title"
:fixed="true"
:autoBack="false"
leftIconColor="#ffffff"
titleStyle="font-weight:bold;"
>
<view
style="margin-top:2px;margin-right:3px;"
slot="right"
>
<view style="border:1rpx solid #ccc;border-radius: 14px;padding:4px 12px;" class="hz-flex-row hz-flex-vertical-mid">
<image @click="navTo('/pages/findPlayer/findPlayer',1,false)" src="../../static/images/ico_find_player.png" class="hz-nav-btn"></image>
<view style="height:20px;border-left:1px solid #ccc;margin-left:8px;margin-right:8px;"></view>
<image @click="navTo('/booking/bookingRecord/bookingRecord',0,false)" src="../../static/images/ico_list.png" class="hz-nav-btn"></image>
</view>
</view>
</u-navbar>
<view class="hz-spacing hz-bg-white">
<view class="hz-card-profile" style="margin-bottom:6px;">
<view class="hz-flex-row">
<view style="width:60%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.playerId")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{ playerData.playerId }}</view>
</view>
<view style="width:40%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.tier")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{ playerData.tierName }}</view>
</view>
</view>
<view class="hz-flex-row hz-mr-t-30">
<view style="width:100%">
<view class="hz-font-color-light hz-font-sm">{{$t("common.name")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{playerData.salutation + " " + playerData.name }}</view>
</view>
</view>
</view>
<view v-for="(item,index) in pendingList" :key="index" class="hz-flex-row hz-pd-30 hz-font-bold hz-font-sm hz-card-booking" style="margin-top:10px;align-items: center;">
<view style="width:100%;">
<view class="hz-flex-row" style="align-items: center;">
<image src="../../static/images/ico_calendar_grey.png" style="width:16px;height:16px;"></image>
<span class="hz-font-md hz-font-bolder" style="margin-left:4px;">{{dateFormat(item.date[0])}} {{$t("common.to")}} {{dateFormat(item.date[item.date.length-1]) }}</span>
</view>
<view class="hz-flex-row" style="margin-top:8px;">
<view class="hz-flex-row" style="width:33%;align-items: center;">
<image src="../../static/images/ico_night_grey.png" style="width:16px;height:16px;"></image>
<span class="hz-font-md hz-font-bolder" style="margin-left:4px;">{{getNight(item.numOfNight)}}</span>
</view>
<view class="hz-flex-row" style="width:33%;align-items: center;">
<image src="../../static/images/ico_room_grey.png" style="width:16px;height:16px;"></image>
<span class="hz-font-md hz-font-bolder" style="margin-left:4px;">{{getRoom(item.numOfRoom)}}</span>
</view>
<view class="hz-flex-row" style="width:34%;justify-content: right;">
<view class="hz-status-pending hz-btn-status hz-font-min hz-text-center" style="width:70%;height:14px;line-height:14px;">{{item.bookingStatus!==undefined && item.bookingStatus!='PN'? 'DUE IN':'PENDING'}}</view>
</view>
</view>
</view>
</view>
<view v-if="waitlist!=null && waitlist.length>1" class="hz-flex-row" style="align-items: center;margin-top:20px;">
<view @click="changeRoom('prev')" style="width:8%;" :class="currentRoomIndex===0? 'hz-disabled':''">
<u-icon name="arrow-left" color="#C39A4B" size="28"></u-icon>
</view>
<view class="hz-text-center hz-font-md hz-font-bolder" style="width:84%;">Waitlist {{currentRoomIndex+1}}</view>
<view @click="changeRoom('next')" style="width:8%;":class="currentRoomIndex===numOfWatilist-1? 'hz-disabled':''">
<u-icon name="arrow-right" color="#C39A4B" size="28"></u-icon>
</view>
</view>
<view v-if="showDateRange" class="hz-flex-row hz-pd-30 hz-font-bold hz-font-md hz-card-extend" style="margin-top:30rpx;align-items: center;">
<view style="width:100%;">
<view class="hz-flex-row" style="align-items: center;">
<image src="../../static/images/ico_calendar.png" style="width:16px;height:16px;"></image>
<span class="hz-font-md hz-font-bolder" style="margin-left:4px;">{{(waitlist[currentRoomIndex].date[0]) +" - " + (waitlist[currentRoomIndex].date[waitlist[currentRoomIndex].date.length-1]) }}</span>
</view>
<view class="hz-flex-row" style="margin-top:8px;">
<view class="hz-flex-row" style="width:33%;align-items: center;">
<image src="../../static/images/ico_night.png" style="width:16px;height:16px;"></image>
<span class="hz-font-md hz-font-bolder" style="margin-left:4px;">{{getNight(waitlist[currentRoomIndex].numOfNight)}}</span>
</view>
<view class="hz-flex-row" style="width:33%;align-items: center;">
<image src="../../static/images/ico_room.png" style="width:16px;height:16px;"></image>
<span class="hz-font-md hz-font-bolder" style="margin-left:4px;">{{getRoom(waitlist[currentRoomIndex].numOfRoom)}}</span>
</view>
<view class="hz-flex-row" style="width:34%;justify-content: right;">
</view>
</view>
</view>
</view>
<view class="hz-spacing hz-mr-t-30" style="margin-bottom:30px;">
<view class="hz-flex-row">
<view style="width:65%">
<view class="hz-font-color-black hz-font-sm">{{$t("common.property")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{bookingData.propertyName}}</view>
</view>
<view style="width:35%">
<view class="hz-font-color-black hz-font-sm">{{$t("newBooking.roomType")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{bookingData.room}}</view>
<!--<view class="hz-font-color-black hz-font-sm">{{$t("common.block")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{bookingData.block}}</view>-->
</view>
</view>
<!--<<view class="hz-flex-row hz-mr-t-30">
<view style="width:65%">
<view class="hz-font-color-black hz-font-sm">{{$t("newBooking.roomType")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{bookingData.room}}</view>
</view>
<view style="width:35%">
view class="hz-font-color-black hz-font-sm">{{$t("newBooking.roomType")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{bookingData.roomTypeCode}}</view>
</view>
</view>-->
<view v-if="(bookingData.specialName!=null && bookingData.specialName!='') || (bookingData.bedTypeName!=null && bookingData.bedTypeName!='')" class="hz-flex-row hz-mr-t-30">
<view style="width:100%">
<view class="hz-font-color-black hz-font-sm">{{$t("newBooking.specialPreference")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{getSpecial(bookingData.specialName,bookingData.bedTypeName)}}</view>
</view>
</view>
<view v-if="bookingData.sharerList!=null && bookingData.sharerList.length>0" class="hz-flex-row hz-mr-t-30">
<view style="width:100%">
<view class="hz-font-color-black hz-font-sm">{{$t("bookingRecord.sharer")}}</view>
<view v-for="(item,index) in bookingData.sharerList" :key="'sharer'+index" class="hz-font-bolder hz-font-lg" >{{getSharer(item.playerId,item.name)}}</view>
</view>
</view>
<view class="hz-flex-row hz-mr-t-30">
<view style="width:65%">
<view class="hz-font-color-black hz-font-sm">{{$t("bookingConfirm.createdOn")}}</view>
<view class="hz-font-bolder hz-font-lg" >{{bookingData.createdOn}}</view>
</view>
<view style="width:35%">
<view class="hz-font-color-black hz-font-sm">{{$t("bookingConfirm.createdBy")}}</view>
<view class="hz-font-bolder hz-font-lg">
{{bookingData.createdByName!=null?bookingData.createdByName:userData.userName}}
</view>
</view>
</view>
<view class="hz-flex-row hz-mr-t-30">
<view style="width:100%">
<view class="hz-font-color-black hz-font-sm">{{$t("newWaitlist.remark")}}</view>
<view class="hz-font-bolder hz-font-md" style="margin-top:4px;">
<u--textarea v-model="remarkList[currentRoomIndex]" :count="true" :maxlength="255" ></u--textarea>
</view>
</view>
</view>
</view>
<view :style="'height:'+footFuncHei+'rpx;'"></view>
</view>
<u-tabbar
:fixed="true"
:placeholder="true"
:safeAreaInsetBottom="true"
customStyle="z-index:100;height:58px;"
>
<view class="book hz-spacing">
<view @click="submitWaitlist" class="hz-btn-danger hz-font-color-white hz-font-lg hz-font-bold hz-text-center">
{{$t("newWaitlist.submitWaitlist")}}
</view>
</view>
</u-tabbar>
</view>
<u-popup
:safeAreaInsetBottom="true"
:safeAreaInsetTop="true"
:mode="'center'"
:round="12"
:show="showMsgBox"
>
<view
:style="'width:'+ windowWidth + 'px;'"
style="padding:30px;"
>
<view class="hz-flex-row" style="justify-content: center;">
<image :src="iconPath" style="width:64px;height:64px;"></image>
</view>
<view class="hz-font-md hz-font-bold hz-text-center" style="margin-top:20px;">
<rich-text v-html="msgStr" style="line-height:26px;"></rich-text>
</view>
<view @click="navToDetail(url)" class="hz-btn hz-font-color-white hz-font-lg hz-font-bold hz-text-center" style="margin-top:20px;">
{{buttonStr}}
</view>
</view>
</u-popup>
</view>
</template>
<script>
import dayjs from '../../uni_modules/uview-ui/libs/util/dayjs.js';
import {formatDate} from '../../common/stringUtils.js';
import {saveBooking,editBooking} from '../../api/bookingApi.js';
export default {
data() {
return {
//数据变量
playerData:null,
bookingData:null,
userData:null,
remarkList:[],
pendingList:[],
waitlist:[],
// 界面变量
title:'',
type:'',
iconPath:'',
msgStr:'',
url:'',
buttonStr:'',
showMsgBox:false,
showList:false,
showDateRange:false,
currentRoomIndex:0,
numOfWatilist:0,
putInWaitlistText:this.$t("bookingConfirm.putInWaitlist"),
windowWidth:0,
footFuncHei:100,
}
},
onLoad(opt) {
// 初始化界面
this.initUI();
this.playerData = uni.getStorageSync("playerData");
this.userData = uni.getStorageSync("userData");
this.getBooking();
},
async onShow() {
// 检查是否登录
// this.isLogin();
},
methods: {
// 數據方法
getBooking(){
this.bookingData = uni.getStorageSync("bookingData");
if(this.bookingData!==null && this.bookingData!==undefined && this.bookingData!==''){
if(this.bookingData.bookType==1){
for(let i=0;i<this.bookingData.extendDate.length;i++){
let dateObj = this.bookingData.extendDate[i];
if(dateObj.checked===true && dateObj.status===1) {
this.numOfWatilist++;
this.waitlist.push(dateObj);
}
if(dateObj.checked===true && dateObj.status===0) {
this.pendingList.push(dateObj);
}
}
}else{
for(let i=0;i<this.bookingData.dateList.length;i++){
let dateObj = this.bookingData.dateList[i];
if(dateObj.checked===true && dateObj.status===1) {
this.numOfWatilist++;
this.waitlist.push(dateObj);
}
if(dateObj.checked===true && dateObj.status===0) {
this.pendingList.push(dateObj);
}
}
}
this.showDateRange = true;
}else{
// 报错
}
},
async submitWaitlist(){
uni.showLoading({
title: this.$t("common.loading")
});
try{
if(this.bookingData.bookType==1){
for(let i=0;i<this.bookingData.extendDate.length;i++){
if(this.bookingData.extendDate[i].checked===true && this.bookingData.extendDate[i].status===1){
this.bookingData.extendDate[i].remark = this.remarkList[0];
this.bookingData.extendDate[i].submit = true;
this.remarkList.splice(0,1);
}
}
}else{
for(let i=0;i<this.bookingData.dateList.length;i++){
if(this.bookingData.dateList[i].checked===true && this.bookingData.dateList[i].status===1){
this.bookingData.dateList[i].remark = this.remarkList[0];
this.bookingData.dateList[i].submit = true;
this.remarkList.splice(0,1);
}
}
}
uni.setStorageSync("bookingData",this.bookingData);
// 保存waitlist
var res = null;
if(this.bookingData.bookType=='1'){
res = await editBooking(this.bookingData);
}else{
res = await saveBooking(this.bookingData);
}
// 如果成功
if(res.success === true){
const resultBookings = res.data;
if(this.numOfWatilist>1){
//this.url = '/booking/bookingGroup/bookingGroup?groupId='+resultBookings[0].groupId;
this.url = '/booking/bookingRecord/bookingRecord';
this.buttonStr = this.$t("bookingConfirm.backToRecords");
}else if(this.numOfWatilist==1){
this.url = '/booking/bookingDetail/bookingDetail?id='+resultBookings[0].id+'&conf=&from=booking';
this.buttonStr = this.$t("newWailist.viewSubmitedWaitlist");
}else{
// 出错
}
this.msgStr = this.$t("newWaitlist.savesuccessful");
this.iconPath = '../../static/images/ico_suc.png';
this.showMsgBox = true;
}else{
this.msgStr = this.$t("common.saveFail"); // 或者其他錯誤信息
this.buttonStr = this.$t("common.ok");
this.iconPath = '../../static/images/ico_err.png';
this.url = '';
this.showMsgBox = true;
}
}catch(e){
console.error(e);
await this.writeLog(this.userData.userId,"save_booking","","[APP][newWaitlist.vue][submitWaitlist][Catch Exception]"+e.errMsg,"","",1,false);
}finally{
uni.hideLoading();
}
},
// 界面方法
navToDetail(url){
if(url!=null && url!==undefined && url!==''){
this.navTo(url,0,false);
}else{
this.showMsgBox = false;
}
},
changeRoom(type){
if(type==='prev' && this.currentRoomIndex>0){
this.currentRoomIndex = this.currentRoomIndex-1;
}
else if(type==='next' && this.currentRoomIndex<this.numOfWatilist-1){
this.currentRoomIndex = this.currentRoomIndex+1;
}
},
initUI() {
this.deviceData = uni.getStorageSync("deviceData");
this.title = this.$t("newWaitlist.title");
this.windowWidth = this.deviceData.windowWidth-130;
// 判斷iphone下方安全區域
const area = this.deviceData.saveArea;
if(area){
this.footFuncHei = 160;
}
},
},
computed:{
getStatusColor(){
return function (booking) {
let operaStatus = null;
if(booking==null){
return '';
}
if(booking.lastOperaStatus!=null){
operaStatus = booking.lastOperaStatus;
}
let approveStatus = null;
if(booking.approveStatus!=null){
approveStatus = booking.approveStatus;
}
// Opera和Approve Status都不为空的情况
if((operaStatus!=null && operaStatus!=undefined) || (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'){
return 'hz-status-pending';
}else if(approveStatus.toUpperCase()==='N'){
if(operaStatus!==null && operaStatus!==undefined && operaStatus!=='' && operaStatus!=='null'){
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-reserved';
}
else
{
return '';
}
}
}else if(approveStatus.toUpperCase()==='W'){
return 'hz-status-waitlist';
}
else
{
if(operaStatus==null) return '';
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-reserved';
}
else
{
return '';
}
}
}
// Opera status为空,Approve Status不为空的情况
else if((operaStatus==null || operaStatus==undefined) && (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'){
return 'hz-status-font-pending';
}else if(approveStatus.toUpperCase()==='W'){
return 'hz-status-font-waitlist';
}else{
return '';
}
}
}
},
getStatusTextColor(){
return function (booking) {
let operaStatus = null;
if(booking==null){
return '';
}
if(booking.lastOperaStatus!=null){
operaStatus = booking.lastOperaStatus;
}
let approveStatus = null;
if(booking.approveStatus!=null){
approveStatus = booking.approveStatus;
}
// Opera和Approve Status都不为空的情况
if((operaStatus!=null && operaStatus!=undefined) || (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'){
return 'hz-status-font-pending';
}else if(approveStatus.toUpperCase()==='N'){
if(operaStatus!==null && operaStatus!==undefined && operaStatus!=='' && operaStatus!=='null'){
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-font-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-font-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-font-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-font-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-font-reserved';
}
else
{
return '';
}
}
}else if(approveStatus.toUpperCase()==='W'){
return 'hz-status-font-waitlist';
}
else
{
if(operaStatus==null) return '';
if(operaStatus.toUpperCase()==='DUE_IN'){
return 'hz-status-font-duein';
}
else if(operaStatus.toUpperCase()==='CHECKED_IN'){
return 'hz-status-font-checkedin';
}
else if(operaStatus.toUpperCase()==='CHECKED_OUT'){
return 'hz-status-font-waitlist';
}
else if(operaStatus.toUpperCase()==='DUE_OUT'){
return 'hz-status-font-dueout';
}
else if(operaStatus.toUpperCase()==='RESERVED'){
return 'hz-status-font-reserved';
}
else
{
return '';
}
}
}
// Opera status为空,Approve Status不为空的情况
else if((operaStatus==null || operaStatus==undefined) && (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN'){
return 'hz-status-font-pending';
}else if(approveStatus.toUpperCase()==='W'){
return 'hz-status-font-waitlist';
}
else{
return '';
}
}
}
},
getStatusText(){
return function (booking) {
let operaStatus = null;
if(booking==null){
return;
}
if(booking.lastOperaStatus!=null){
operaStatus = booking.lastOperaStatus;
}
let approveStatus = null;
if(booking.approveStatus!=null){
approveStatus = booking.approveStatus;
}
if((operaStatus!=null && operaStatus!=undefined) || (approveStatus!=null && approveStatus!=undefined))
{
if(approveStatus.toUpperCase()==='PN' || approveStatus.toUpperCase()==='W'){
if(approveStatus!==null && approveStatus!==undefined && approveStatus!=='' && approveStatus!=='null')
return mapApproveStatus(approveStatus.toUpperCase());
}else if( approveStatus.toUpperCase()==='N'){
if(operaStatus!==null && operaStatus!==undefined && operaStatus!=='' && operaStatus!=='null')
return mapOperaStatus(operaStatus.toUpperCase());
}
}
else if((operaStatus==null || operaStatus==undefined) && (approveStatus!=null && approveStatus!=undefined))
{
return mapApproveStatus(approveStatus.toUpperCase());
}
}
},
getSpecial(){
return function (specialName,bedTypeName) {
let str = ''
if(bedTypeName!=null && bedTypeName!=''){
str = bedTypeName;
}
if(specialName!=null && specialName!=''){
if(str == ''){
str = specialName;
}else{
str = str+", "+ specialName;
}
}
return str;
}
},
getSharer(){
return function (playerId,name) {
let id = null;
if(playerId!==null && playerId!==undefined && playerId!=='' && playerId!=='null'){
id = playerId;
}
let na = null;
if(name!==null && name!==undefined && name!=='' && name!=='null'){
na = name;
}
let res = '';
if(id!=null){
res = id;
}
if(na!=null){
if(res!==''){
res = res + ', ' + na;
}else{
res = na;
}
}
return res;
}
},
dateFormat() {
return function (date) {
if (date != undefined) {
let weekNum = dayjs(date).day();
let week = '';
switch(weekNum){
case 1:
week='Mon'
break;
case 2:
week='Tue';
break;
case 3:
week='Wed';
break;
case 4:
week='Thu';
break;
case 5:
week='Fri';
break;
case 6:
week='Sat';
break;
case 0:
week='Sun';
break;
}
return '('+week+') ' + dayjs(date).format("YYYY-MM-DD");
}
}
},
getNight(){
return function (num) {
if(num!==null && num!==undefined && num!=='null')
{
if(num>1){
return num + " " + this.$t("common.nights");
}else{
return num + " " + this.$t("common.night");
}
}
else
return '';
}
},
getRoom(){
return function (num) {
if(num!==null && num!==undefined && num!=='null')
{
if(num>1){
return num + " " + this.$t("common.rooms");
}else{
return num + " " + this.$t("common.room");
}
}
else
return '';
}
},
}
}
</script>
<style lang="scss" scoped>
</style>
File diff suppressed because it is too large Load Diff
+187
View File
@@ -0,0 +1,187 @@
/**
* 与后端 EncryptUtil.aesEncryptToBase64(AES-GCM,12 字节 IV,16 字节 tag)一致。
* App 端 WebView 往往无 crypto.subtle,需用纯 JS 解密。
*/
import { gcm } from '@noble/ciphers/aes.js';
import { sha256 } from '@noble/hashes/sha2.js';
// Polyfill for TextEncoder/TextDecoder in Weex environment
class TextEncoderPolyfill {
encode(text) {
const arr = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) {
arr[i] = text.charCodeAt(i) & 0xff;
}
return arr;
}
}
class TextDecoderPolyfill {
decode(uint8Array) {
let str = '';
let i = 0;
while (i < uint8Array.length) {
const byte1 = uint8Array[i];
if (byte1 < 0x80) {
// 单字节 ASCII
str += String.fromCharCode(byte1);
i++;
} else if ((byte1 & 0xe0) === 0xc0) {
// 双字节 UTF-8
const byte2 = uint8Array[i + 1];
const code = ((byte1 & 0x1f) << 6) | (byte2 & 0x3f);
str += String.fromCharCode(code);
i += 2;
} else if ((byte1 & 0xf0) === 0xe0) {
// 三字节 UTF-8
const byte2 = uint8Array[i + 1];
const byte3 = uint8Array[i + 2];
const code = ((byte1 & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
str += String.fromCharCode(code);
i += 3;
} else if ((byte1 & 0xf8) === 0xf0) {
// 四字节 UTF-8(需要代理对)
const byte2 = uint8Array[i + 1];
const byte3 = uint8Array[i + 2];
const byte4 = uint8Array[i + 3];
let code = ((byte1 & 0x07) << 18) | ((byte2 & 0x3f) << 12) | ((byte3 & 0x3f) << 6) | (byte4 & 0x3f);
// 转换为 UTF-16 代理对
code -= 0x10000;
const high = 0xd800 + (code >> 10);
const low = 0xdc00 + (code & 0x3ff);
str += String.fromCharCode(high, low);
i += 4;
} else {
// 非法字节,跳过
str += String.fromCharCode(byte1);
i++;
}
}
return str;
}
}
const TextEncoder = typeof globalThis !== 'undefined' && globalThis.TextEncoder ? globalThis.TextEncoder : TextEncoderPolyfill;
const TextDecoder = typeof globalThis !== 'undefined' && globalThis.TextDecoder ? globalThis.TextDecoder : TextDecoderPolyfill;
/** 与后端 EncryptUtil 一致:去掉 BOM/空白,避免与 SHA-256(UTF-8) 密钥不一致 */
function normalizeSecret(secret) {
if (secret == null || typeof secret !== 'string') {
return secret;
}
let s = secret.trim();
if (s.length > 0 && s.charCodeAt(0) === 0xfeff) {
s = s.slice(1);
}
return s;
}
/**
* x-www-form-urlencoded /部分网关会把 Base64 里的 "+" 变成空格;JSON 一般不受影响。
*/
function normalizeBase64Segment(seg) {
if (seg == null || seg === '') {
return seg;
}
let s = String(seg).trim().replace(/\s/g, '+');
s = s.replace(/-/g, '+').replace(/_/g, '/');
const pad = s.length % 4;
if (pad !== 0) {
s += '='.repeat(4 - pad);
}
return s;
}
function base64ToUint8Array(b64) {
const normalized = normalizeBase64Segment(b64);
if (typeof atob === 'function') {
const bin = atob(normalized);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) {
out[i] = bin.charCodeAt(i) & 0xff;
}
return out;
}
if (typeof uni !== 'undefined' && uni.base64ToArrayBuffer) {
return new Uint8Array(uni.base64ToArrayBuffer(normalized));
}
throw new Error('cfgSettingCrypto: no base64 decoder');
}
function splitIvAndCipher(encryptedText) {
const idx = encryptedText.indexOf(':');
if (idx <= 0 || idx === encryptedText.length - 1) {
return null;
}
return {
ivB64: encryptedText.slice(0, idx),
cipherB64: encryptedText.slice(idx + 1),
};
}
async function decryptWithSubtle(encryptedText, secret) {
const parts = splitIvAndCipher(encryptedText);
if (!parts) {
throw new Error('cfgSettingCrypto: invalid iv:cipher format');
}
const ivBytes = base64ToUint8Array(parts.ivB64);
const cipherBytes = base64ToUint8Array(parts.cipherB64);
const keyRaw = new TextEncoder().encode(normalizeSecret(secret));
const keyHash = await globalThis.crypto.subtle.digest('SHA-256', keyRaw);
const aesKey = await globalThis.crypto.subtle.importKey(
'raw',
keyHash,
{ name: 'AES-GCM' },
false,
['decrypt']
);
const decrypted = await globalThis.crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: ivBytes, tagLength: 128 },
aesKey,
cipherBytes
);
return new TextDecoder().decode(decrypted);
}
function decryptWithNoble(encryptedText, secret) {
const parts = splitIvAndCipher(encryptedText);
if (!parts) {
throw new Error('cfgSettingCrypto: invalid iv:cipher format');
}
const ivBytes = base64ToUint8Array(parts.ivB64);
const cipherBytes = base64ToUint8Array(parts.cipherB64);
const keyBytes = sha256(new TextEncoder().encode(normalizeSecret(secret)));
const decipher = gcm(keyBytes, ivBytes);
const plainBytes = decipher.decrypt(cipherBytes);
return new TextDecoder().decode(plainBytes);
}
/**
* @param {string} encryptedText 格式 base64(iv):base64(ciphertext||tag)
* @param {string} secret 与后端 allow_key 一致
* @returns {Promise<string>}
*/
export async function decryptCfgSettingValue(encryptedText, secret) {
if (!encryptedText || !secret || encryptedText.indexOf(':') === -1) {
return encryptedText;
}
if (!splitIvAndCipher(encryptedText)) {
return encryptedText;
}
try {
if (globalThis.crypto && globalThis.crypto.subtle) {
const plain = await decryptWithSubtle(encryptedText, secret);
if (plain) {
return plain;
}
}
} catch (e) {
console.warn('[cfgSettingCrypto] WebCrypto 解密失败,改用 @noble/ciphers', e);
}
try {
return decryptWithNoble(encryptedText, secret);
} catch (e) {
console.error('[cfgSettingCrypto]解密失败', e);
return encryptedText;
}
}
+39
View File
@@ -0,0 +1,39 @@
class config {
constructor() {
//local
this.internalUrl = 'https://localhost:9086';
// mgm web DEV
// this.internalUrl = 'https://localhost';
// willtech DEV
// this.internalUrl = 'https://47.238.46.81';
// MGM APP DEV
// this.internalUrl = 'https://dlahcadev.mcmsapoc.com';
//this.version = "beta 2.0";
//ali ECS
// this.internalUrl = 'https://mcrm.willtechmacau.com:9086';
this.externalUrl = 'https://mp.mixixili.cn';
this.debugMode = true;
this.apiPath = '/api';
this.internalSSOUrl = 'https://adserver.willtechmacau.com';
this.externalSSOUrl = 'https://adserver.willtechmacau.com';
this.internalTag = true;
this.originUrl = "MGM_CRM_APP";
this.appId='MGM_CRM_APP';
this.allowKey='U2FsdGVkX19JXgsp9IZ+cr6P67KVShdWWRX5niRURIk=';
//dev
// this.internalUrl = 'https://hca.mcmsapoc.com';
// this.internalUrl = 'https://localhost';
this.version = "Dev 1.64";
//prod
//this.internalUrl = 'https://hostcrmapp.mgm.mo';
//this.version = "v2.0";
this.resourceCallBackUrl = "hostcrmapp_dev";
this.emailExt = "";// 如果是dev的時候設置成空字符串,讓他們自己輸入
}
}
export default config
+324
View File
@@ -0,0 +1,324 @@
/**
* 坐标转换问题分析和解决方案 - 精确修正
* lc 2025-07-15
*/
class FixedCoordinateConverter {
constructor() {
this.a = 6378245.0;
this.ee = 0.00669342162296594323;
this.PI = Math.PI;
// 精确偏移校正参数(基于实际测试数据)
this.OFFSET_CORRECTIONS = {
// 经度偏移校正
lngCorrection: -0.00003,
// 纬度偏移校正
latCorrection: 0.0003
};
}
/**
* 标准算法实现
*/
wgs84ToGcj02Standard(wgsLat, wgsLng) {
if (!this.isInChina(wgsLat, wgsLng)) {
return { lat: wgsLat, lng: wgsLng };
}
let dLat = this.transformLat(wgsLng - 105.0, wgsLat - 35.0);
let dLng = this.transformLng(wgsLng - 105.0, wgsLat - 35.0);
const radLat = wgsLat / 180.0 * this.PI;
let magic = Math.sin(radLat);
magic = 1 - this.ee * magic * magic;
const sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((this.a * (1 - this.ee)) / (magic * sqrtMagic) * this.PI);
dLng = (dLng * 180.0) / (this.a / sqrtMagic * Math.cos(radLat) * this.PI);
return {
lat: wgsLat + dLat,
lng: wgsLng + dLng
};
}
wgs84ToGcj02Fixed(wgsLat, wgsLng) {
if (!this.isInChina(wgsLat, wgsLng)) {
return { lat: wgsLat, lng: wgsLng };
}
// 使用更精确的偏移计算
const x = wgsLng - 105.0;
const y = wgsLat - 35.0;
let dLat = this.transformLatFixed(x, y);
let dLng = this.transformLngFixed(x, y);
const radLat = wgsLat / 180.0 * this.PI;
const sinLat = Math.sin(radLat);
const cosLat = Math.cos(radLat);
// 修正魔法数计算
const magic = 1.0 - this.ee * sinLat * sinLat;
const sqrtMagic = Math.sqrt(magic);
// 使用更精确的转换公式
const M = this.a * (1.0 - this.ee) / (magic * sqrtMagic); // 子午圈曲率半径
const N = this.a / sqrtMagic; // 卯酉圈曲率半径
dLat = (dLat * 180.0) / (M * this.PI);
dLng = (dLng * 180.0) / (N * cosLat * this.PI);
// 应用精确偏移校正
const correctedLat = wgsLat + dLat + this.OFFSET_CORRECTIONS.latCorrection;
const correctedLng = wgsLng + dLng + this.OFFSET_CORRECTIONS.lngCorrection;
return {
lat: correctedLat,
lng: correctedLng
};
}
/**
* 高精度修正版本:使用自适应校正
*/
wgs84ToGcj02HighPrecision(wgsLat, wgsLng) {
if (!this.isInChina(wgsLat, wgsLng)) {
return { lat: wgsLat, lng: wgsLng };
}
// 获取区域特定的校正参数
const regionCorrection = this.getRegionSpecificCorrection(wgsLat, wgsLng);
const x = wgsLng - 105.0;
const y = wgsLat - 35.0;
let dLat = this.transformLatFixed(x, y);
let dLng = this.transformLngFixed(x, y);
const radLat = wgsLat / 180.0 * this.PI;
const sinLat = Math.sin(radLat);
const cosLat = Math.cos(radLat);
const magic = 1.0 - this.ee * sinLat * sinLat;
const sqrtMagic = Math.sqrt(magic);
const M = this.a * (1.0 - this.ee) / (magic * sqrtMagic);
const N = this.a / sqrtMagic;
dLat = (dLat * 180.0) / (M * this.PI);
dLng = (dLng * 180.0) / (N * cosLat * this.PI);
// 应用区域特定校正
const correctedLat = wgsLat + dLat + regionCorrection.latCorrection;
const correctedLng = wgsLng + dLng + regionCorrection.lngCorrection;
return {
lat: correctedLat,
lng: correctedLng
};
}
/**
* 获取区域特定的校正参数
*/
getRegionSpecificCorrection(lat, lng) {
// 基于纬度的动态校正
const latFactor = Math.cos(lat * this.PI / 180);
// 默认校正值(基于实际测试)
let latCorrection = this.OFFSET_CORRECTIONS.latCorrection;
let lngCorrection = this.OFFSET_CORRECTIONS.lngCorrection * latFactor;
// 针对不同地区的微调
if (lat >= 39.0 && lat <= 41.0 && lng >= 115.0 && lng <= 118.0) {
// 北京地区特殊校正
latCorrection = 0.00220;
lngCorrection = -0.00140 * latFactor;
} else if (lat >= 30.5 && lat <= 32.0 && lng >= 120.5 && lng <= 122.5) {
// 上海地区特殊校正
latCorrection = 0.00230;
lngCorrection = -0.00150 * latFactor;
} else if (lat >= 22.0 && lat <= 24.0 && lng >= 112.5 && lng <= 115.0) {
// 广州深圳地区特殊校正
latCorrection = 0.00240;
lngCorrection = -0.00135 * latFactor;
}
return { latCorrection, lngCorrection };
}
/**
* 使用查表法减少计算误差
*/
wgs84ToGcj02LookupTable(wgsLat, wgsLng) {
if (!this.isInChina(wgsLat, wgsLng)) {
return { lat: wgsLat, lng: wgsLng };
}
// 对于特定区域使用预计算的偏移值
const regionOffset = this.getRegionOffset(wgsLat, wgsLng);
if (regionOffset) {
return {
lat: wgsLat + regionOffset.latOffset,
lng: wgsLng + regionOffset.lngOffset
};
}
// 否则使用高精度算法
return this.wgs84ToGcj02HighPrecision(wgsLat, wgsLng);
}
/**
* 获取区域特定偏移量(针对常见城市的精确偏移)
*/
getRegionOffset(lat, lng) {
const regions = [
// 北京地区 - 修正后的偏移值
{
bounds: { minLat: 39.4, maxLat: 41.0, minLng: 115.4, maxLng: 117.5 },
latOffset: 0.00580, // 修正向南偏移
lngOffset: 0.00506 // 修正向东偏移
},
// 上海地区
{
bounds: { minLat: 30.7, maxLat: 31.9, minLng: 120.9, maxLng: 122.2 },
latOffset: 0.00590,
lngOffset: 0.00496
},
// 广州地区
{
bounds: { minLat: 22.5, maxLat: 23.9, minLng: 112.9, maxLng: 114.8 },
latOffset: 0.00600,
lngOffset: 0.00486
},
// 深圳地区
{
bounds: { minLat: 22.4, maxLat: 22.8, minLng: 113.7, maxLng: 114.6 },
latOffset: 0.00595,
lngOffset: 0.00491
}
];
for (const region of regions) {
if (lat >= region.bounds.minLat && lat <= region.bounds.maxLat &&
lng >= region.bounds.minLng && lng <= region.bounds.maxLng) {
return region;
}
}
return null;
}
/**
* 修正的纬度转换函数
*/
transformLatFixed(x, y) {
let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y +
0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * this.PI) +
20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(y * this.PI) +
40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(y / 12.0 * this.PI) +
320.0 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
return ret;
}
/**
* 修正的经度转换函数
*/
transformLngFixed(x, y) {
let ret = 300.0 + x + 2.0 * y + 0.1 * x * x +
0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * this.PI) +
20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(x * this.PI) +
40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(x / 12.0 * this.PI) +
300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
return ret;
}
transformLat(x, y) {
return this.transformLatFixed(x, y);
}
transformLng(x, y) {
return this.transformLngFixed(x, y);
}
isInChina(lat, lng) {
return lng >= 72.004 && lng <= 137.8347 &&
lat >= 0.8293 && lat <= 55.8271;
}
/**
* 计算偏移距离(米)
*/
calculateOffsetDistance(originalLat, originalLng, convertedLat, convertedLng) {
const latDiffMeters = (convertedLat - originalLat) * 111000;
const lngDiffMeters = (convertedLng - originalLng) * 111000 * Math.cos(originalLat * this.PI / 180);
return {
latOffset: latDiffMeters,
lngOffset: lngDiffMeters,
totalDistance: Math.sqrt(latDiffMeters * latDiffMeters + lngDiffMeters * lngDiffMeters)
};
}
/**
* 比较不同算法的转换结果
*/
compareAlgorithms(wgsLat, wgsLng) {
const standard = this.wgs84ToGcj02Standard(wgsLat, wgsLng);
const fixed = this.wgs84ToGcj02Fixed(wgsLat, wgsLng);
const highPrecision = this.wgs84ToGcj02HighPrecision(wgsLat, wgsLng);
const lookup = this.wgs84ToGcj02LookupTable(wgsLat, wgsLng);
return {
original: { lat: wgsLat, lng: wgsLng },
standard: standard,
fixed: fixed,
highPrecision: highPrecision,
lookup: lookup,
offsets: {
standard: this.calculateOffsetDistance(wgsLat, wgsLng, standard.lat, standard.lng),
fixed: this.calculateOffsetDistance(wgsLat, wgsLng, fixed.lat, fixed.lng),
highPrecision: this.calculateOffsetDistance(wgsLat, wgsLng, highPrecision.lat, highPrecision.lng),
lookup: this.calculateOffsetDistance(wgsLat, wgsLng, lookup.lat, lookup.lng)
}
};
}
/**
* 验证修正效果
*/
validateCorrection(wgsLat, wgsLng, expectedGcjLat, expectedGcjLng) {
const result = this.wgs84ToGcj02Fixed(wgsLat, wgsLng);
const error = this.calculateOffsetDistance(expectedGcjLat, expectedGcjLng, result.lat, result.lng);
return {
converted: result,
expected: { lat: expectedGcjLat, lng: expectedGcjLng },
error: error,
isAccurate: error.totalDistance < 10 // 误差小于10米认为准确
};
}
}
// 导出修正版本
if (typeof module !== 'undefined' && module.exports) {
module.exports = FixedCoordinateConverter;
}
if (typeof window !== 'undefined') {
window.FixedCoordinateConverter = FixedCoordinateConverter;
}
+41
View File
@@ -0,0 +1,41 @@
function mapOperaStatus(status){
if(status=="DUE_IN"){
return 'DUE IN';
}else if(status=="CHECKED_IN"){
return 'CHECKED IN';
}else if(status=="DUE_OUT"){
return 'DUE OUT';
}else if(status=="CHECKED_OUT"){
return 'CHECKED OUT';
}else if(status=="RESERVED"){
return 'RESERVED';
}
else{
return status;
}
}
function mapApproveStatus(status){
if(status=="PN"){
return 'PENDING';
}else if(status=="N"){
return 'CONFIRMED';
}else if(status=="W"){
return 'PENDING WAITLIST';
}else if(status=="WA"){
return 'APPROVED';
}else if(status=="WC"){
return 'WAITLIST CANCELLED';
}else if(status=="F"){
return 'FAILED';
}else if(status=="FC"){
return 'FAILED COMPLETE';
}else if(status=="AP"){
return 'PENDING APPROVAL';
}else{
return status;
}
}
export {
mapApproveStatus,
mapOperaStatus,
}
+201
View File
@@ -0,0 +1,201 @@
import {refreshToken} from '../api/commonApi.js'
import dayjs from '../uni_modules/uview-ui/libs/util/dayjs.js';
// 此vm参数为页面的实例,可以通过它引用vuex中的变量
module.exports = (vm) => {
// 请求拦截
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
config.data = config.data || {}
// 根据custom参数中配置的是否需要token,添加对应的请求头
// #ifdef APP-PLUS
if(
config.url!==undefined && config.url!==''
&& config.url.indexOf('logout')==-1
&& config.url.indexOf('Logout')==-1
&& config.url.indexOf('login')==-1
&& config.url.indexOf('Login')==-1
&& config.url.indexOf('setting')==-1
&& config.url.indexOf('regionRestrict')==-1
&& config.url.indexOf('refresh_token')==-1
&& config.url.indexOf('adfs')==-1
&& config.url.indexOf('/me')==-1
&& config.url.indexOf('sys_setting/get_list')==-1
&& config.url.indexOf('sso/get_sso_token_by_code')==-1
&& config.url.indexOf('sso/user_sso_login')==-1
&& config.url.indexOf('sso/mock_user_sso_login')==-1
&& config.url.indexOf('write_log')==-1
)
{
let siteData = uni.getStorageSync("siteData");
//模拟内网登录 打包删除
// siteData.internalTag=true;
//模拟内网登录 打包删除
if(siteData!==undefined && siteData!==null && siteData.internalTag===false)
{
getApp().checkLocationAndVPN();
}
}
// #endif
if(config?.custom?.auth) {
const token = uni.getStorageSync("token")
const clientId = uni.getStorageSync("clientId")
config.header.Authorization = token;
config.header.ClientId = clientId;
// #ifdef APP-PLUS
config.header.Origin = config.custom.origin;
// #endif
if(config.url.indexOf('refresh_token')==-1 ){
// checkToken();
}else{
config.header.RefreshToken = uni.getStorageSync("refreshToken")
}
}
return config
}, config => { // 可使用async await 做异步操作
return Promise.reject(config)
})
// 响应拦截
uni.$u.http.interceptors.response.use((response) => {
/* 对响应成功做点什么 可使用async await 做异步操作*/
const data = response.data
// 自定义参数
// const custom = response.config?.custom
if (data.code != 0) {
// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
if (data.success==false && data.message) {
console.log(data.message)
}
let url = response.config.url
let isCheck = (url!==undefined && url!==''
&& url.indexOf('logout')==-1
&& url.indexOf('Logout')==-1
&& url.indexOf('login')==-1
&& url.indexOf('Login')==-1
&& url.indexOf('setting')==-1
&& url.indexOf('regionRestrict')==-1
&& url.indexOf('refresh_token')==-1
&& url.indexOf('adfs')==-1
&& url.indexOf('/me')==-1
&& url.indexOf('sys_setting/get_list')==-1
&& url.indexOf('sso/get_sso_token_by_code')==-1
&& url.indexOf('save_confirm_log')==-1
&& url.indexOf('write_log')==-1);
if(isCheck){
checkIP(response.header)
}
if(url.indexOf('mock_user_sso_login')!=-1){
checkIP(response.header)
}
// // 如果需要catch返回,则进行reject
// if (custom?.catch) {
// return Promise.reject(data)
// } else {
// // 否则返回一个pending中的promise,请求不会进入catch中
// return new Promise(() => {})
// }
}
return data === undefined ? {} : data
}, (error) => {
console.log(error)
if( error.errMsg=="request:ok") {
error.errMsg= "request:fail";
if(error.data!=undefined){
if(error.data.message!=undefined){
if(error.data.message=="The token was expected to have 3 parts, but got 1."){
uni.$u.toast(error.errMsg)
kickout()
}
}
}
}
if(error.errMsg!==undefined && error.errMsg!=="request:fail" && error.errMsg!=="request:ok" && error.errMsg.indexOf('-1')<=0 && !error.errMsg.includes("request:fail abort")){
uni.$u.toast(error.errMsg)
}
switch (error.statusCode) {
case 403:
break;
case 400:
kickout()
case 401:
if(error.config.url.indexOf('refresh_token')==-1 && error.config.url.indexOf('logout')==-1){
return tokenRefresh().then(_ => {
error.config.header.Authorization = uni.getStorageSync("token");
error.config.header.RefreshToken = uni.getStorageSync("refreshToken")
error.config.baseURL = undefined;
return uni.$u.http.request(error.config);
})
}else{
kickout()
}
default:
break;
}
return Promise.reject(error)
})
}
function tokenRefresh(){
let oldToken = uni.getStorageSync("token");
if (oldToken !== null && oldToken !== '') {
return refreshToken({})
.then((data) => {
uni.setStorageSync("token",data.accessToken);
uni.setStorageSync("tokenTime",dayjs().unix());
return Promise.resolve(true)
})
.catch(error => {
kickout()
})
} else {
kickout()
}
}
function checkToken(){
let now = Math.floor(new Date().getTime() / 1000);
let tokenTime = uni.getStorageSync("tokenTime");
let token = uni.getStorageSync("token")
//4 min refresh token
if(token!="" && now - tokenTime>240){
tokenRefresh()
}
}
function kickout() {
uni.removeStorageSync("userData");
uni.removeStorageSync("token");
uni.removeStorageSync("idToken");
uni.removeStorageSync("clientId");
uni.removeStorageSync("refreshToken");
uni.redirectTo({
url:'/pages/login/login'
})
}
function checkIP(header){
let isInternal = header.IsInternal
let macauIP = header.MacauIP
//console.log(header);
if(isInternal!=undefined){
let internal = false;
if(isInternal=="true") internal = true;
let siteData = uni.getStorageSync("siteData");
if(siteData){
siteData.internalTag = internal;
if(macauIP!=undefined && macauIP!="" && macauIP == "true")
siteData.macauIp = true;
else
siteData.macauIp = false;
uni.setStorageSync("siteData",siteData);
}
/*if(!internal){
if(macauIP!=undefined && macauIP!="" && macauIP == "false"){
getApp().navTo('/pages/regionRestrict/regionRestrict?type=7',0,false); //8
}
}*/
}
}
+160
View File
@@ -0,0 +1,160 @@
//--------------------------------------------------------------
//LC
//2021-10-31
//--------------------------------------------------------------
//校验银行卡号,银行卡校验规则(Luhn算法)
function isBankNo(value) {
if (value == "" || !isPositiveInteger(value)) return false;
var wei = [],
sumOdd = 0,
sumEven = 0,
length = value.length;
for (var j = 0; j < length; j++) {
wei[j] = parseInt(value.substring(length - j - 1, length - j)); // 从最末一位开始提取,每一位上的数值
}
for (var i = 0; i < length / 2; i++) {
sumOdd += wei[2 * i];
if (wei[2 * i + 1] * 2 > 9) wei[2 * i + 1] = wei[2 * i + 1] * 2 - 9;
else wei[2 * i + 1] *= 2;
sumEven += wei[2 * i + 1];
}
return (sumOdd + sumEven) % 10 == 0;
}
//验证手机号
function isPhone(phone){
let reg = /^[1][3-9][0-9]{9}$/
if(reg.test(phone)){
return true;
}else{
return false;
}
}
//验证
//正整数
function isInteger(value) {
return /^[1-9][0-9]*$/.test(value);
}
//浮点类型
function isFloat(num) {
var reg = /^\d+(?=\.{0,1}\d+$|$)/
num=num.replace(/\.\d{2,}$/,num.substr(num.indexOf('.'),3))//删除小数点后两位
return reg.test(num) ;
}
//date类型转string,就是2019-10-10 12:00:00这样,date转时间戳就new Date().valueOf()
function formatDate (date,type) {
if(type=="long")
return date.getFullYear()+'-'+(parseInt(date.getMonth())+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds()
else
return date.getFullYear()+'-'+(parseInt(date.getMonth())+1)+'-'+date.getDate()
}
//是否身份证
function isIdCard (num) {
let reg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
return reg.test(reg)
}
//密码必须是大小写英文加数字
function isPassword(pass) {
if(pass.length <8 || pass.length >20){
return false;
}
var str = pass;
var regexpUperStr = /[A-Z]+/;
var reexpLowerStr = /[a-z]+/;
var regexpNum = /\d+/;
var uperStrFlag = regexpUperStr.test(str);
var lowerStrFlag = reexpLowerStr.test(str);
var numFlag = regexpNum.test(str);
if (uperStrFlag == true && lowerStrFlag == true && numFlag == true)
return true;
else
return false;
}
//验证昵称
function isNickname(nickname){
if(nickname.length <2 || nickname.length >16){
return false;
}
var regex = /^(\w|[\u4E00-\u9FA5])*$/;
var res = regex.test(nickname);
if(res==true){
return true;
}else{
return false;
}
}
var minute = 1000 * 60;
var hour = minute *60;
var day = hour *24;
var week = day * 7;
var month = day * 30;
function getTimer(stringTime){
var time1 = new Date().getTime();//当前的时间戳
stringTime = stringTime.replace(/-/g,'/'); //IOS不支持-格式时间,只支持/格式时间
var time2 = Date.parse(new Date(stringTime));//指定时间的时间戳
var time = time1 - time2;
var result = null;
if(time < 0){
return "";
}else if(time/month >= 1){
result = parseInt(time/month) + "月前";
}else if(time/week >= 1){
result = parseInt(time/week) + "周前";
}else if(time/day >= 1){
result = parseInt(time/day) + "天前";
}else if(time/hour >= 1){
result = parseInt(time/hour) + "小时前";
}else if(time/minute >= 1){
result = parseInt(time/minute) + "分钟前";
}else {
result = "刚刚";
}
return result;
}
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r != null) return unescape(r[2]);
return null;
}
function getParam(url,name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = url.substr(1).match(reg);
if(r != null) return unescape(r[2]);
return null;
}
function formatRichText(html){
let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = newContent.replace(/<br[^>]*\/>/gi, '');
newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0;"');
return newContent;
}
export {
isBankNo,
isInteger,
isFloat,
formatDate,
isIdCard,
isPhone,
isPassword,
isNickname,
getTimer,
getUrlParam,getParam,
formatRichText,
}
+112
View File
@@ -0,0 +1,112 @@
<template>
<view>
<u-navbar
:safeAreaInsetTop="true"
:placeholder="true"
:title="userName"
:fixed="true"
:autoBack="false"
leftIconColor="#C39A4B"
bgColor="#C39A4B"
titleStyle="max-width:none;width:auto;font-weight:bold;color:#ffffff;"
>
<view @tap="logout"
style="margin-top:2px;margin-right:3px;"
slot="right"
>
<image src="../../static/images/ico_exit.png" style="width:24px;height:24px;"></image>
</view>
</u-navbar>
</view>
</template>
<script>
import {logout} from '../../api/commonApi.js';
const ADFS_LOGOUT_URL = 'https://adfs.mgm.mo/adfs/ls/?wa=wsignout1.0&wtrealm=mgm_mobilecrm_app&wreply=https://hostcrmapp.mgm.mo/sso_callback/logout';
export default {
name:"mgmHeader",
data() {
return {
userName:'',
siteData:null,
userData:null
};
},
mounted() {
this.siteData = uni.getStorageSync("siteData");
this.userData = uni.getStorageSync("userData");
this.userName = this.userData.userName + ", " + this.userData.userId;
this.isLogin();
},
methods:{
updateUserData() {
this.userData = uni.getStorageSync("userData");
if (this.userData) {
this.userName = this.userData.userName + ", " + this.userData.userId;
} else {
this.userName = '';
}
},
async logout(){
uni.showLoading({
title: this.$t("common.loading")
});
try{
let params = {};
const res = await logout(params);
if(res.success == true){
if(res.data !== null){
uni.setTabBarItem({
index:0,
visible:false
});
uni.setTabBarItem({
index:1,
visible:false
});
uni.setTabBarItem({
index:2,
visible:false
});
if(this.siteData.mockSSO==false&&!this.siteData.internalTag){
//this.logoutWithADFSApp()
uni.redirectTo({
url:'/pages/azureLogout/azureLogout'
});
}else{
uni.removeStorageSync("userData");
uni.removeStorageSync("token");
uni.removeStorageSync("idToken");
this.navTo('/pages/login/login',2,false);
}
}
}else{
if(this.siteData.mockSSO==false&&!this.siteData.internalTag){
//this.logoutWithADFSApp()
uni.redirectTo({
url:'/pages/azureLogout/azureLogout'
});
}else{
uni.removeStorageSync("userData");
uni.removeStorageSync("token");
uni.removeStorageSync("idToken");
this.navTo('/pages/login/login',2,false);
}
}
}catch(e){
console.error(e);
uni.$u.toast(e.errMsg,5000);
var request = e.config!=undefined?JSON.stringify(e.config):"";
var response = e.data!=undefined?JSON.stringify(e.data):"";
await this.writeLog(this.userData.userId,"logout","","[APP][header.vue][logout][Catch Exception]"+e.errMsg,request,response,1,false);
}finally{
uni.hideLoading();
}
}
}
}
</script>
<style>
</style>
+78
View File
@@ -0,0 +1,78 @@
<template>
<view class="checkbox" :class="isOpen ? 'active' : ''" @click="handleToggle">
<text v-show="isOpen" style="padding-bottom:1px;">MASS</text>
<view class="circle"></view>
<text v-show="!isOpen" style="padding-bottom:1px;">IM</text>
</view>
</template>
<script>
export default {
props: {
isOpen: {
required: true,
type: Boolean,
default: false
}
},
data() {
return {};
},
methods: {
handleToggle() {
this.$emit('toggle');
}
}
};
</script>
<style scoped lang="scss">
.active {
background-color: #bd9c59 !important;
> .circle {
transform: translateX(92rpx); // 移动到右侧的距离
}
}
.checkbox {
width: 130rpx;
height: 40rpx;
padding: 4rpx;
border-radius: 24rpx;
background-color: #bd9c59; // 默认为灰色
display: flex;
justify-content: flex-start;
align-items: center;
position: relative; // 添加相对定位
> .circle {
width: 40rpx;
height: 40rpx;
background-color: white;
border-radius: 50%;
transition: transform 0.3s ease; // 添加过渡效果
position: absolute; // 使用绝对定位
left: 4rpx; // 左侧起始位置
}
> text {
flex: 1;
font-size: 26rpx;
margin-top:1px;
color: white;
position: relative; // 确保文本在圆形按钮上方
z-index: 1;
&:first-of-type {
text-align: left;
margin-left: 16rpx;
}
&:last-of-type {
text-align: right;
margin-right: 16rpx;
}
}
}
</style>
@@ -0,0 +1,20 @@
<template>
<view>
</view>
</template>
<script>
export default {
name:"playerInfoForBooking",
data() {
return {
};
}
}
</script>
<style>
</style>
@@ -0,0 +1,122 @@
<template>
<view v-if="showWatermark" class="watermark-container">
<view class="watermark-row" v-for="(row, rowIndex) in watermarkRows" :key="'row-' + rowIndex">
<text
class="watermark-text"
v-for="(col, colIndex) in watermarkCols"
:key="'col-' + colIndex"
:style="getWatermarkStyle(rowIndex, colIndex)"
>
{{ watermarkContent }}
</text>
</view>
</view>
</template>
<script>
export default {
name: 'SimpleWatermark',
data() {
return {
showWatermark: false,
watermarkContent: '',
watermarkRows: 8, // 竖直方向显示8行
watermarkCols: 2 // 水平方向显示2列
}
},
methods: {
getWatermarkStyle(rowIndex, colIndex) {
// 计算每个水印的位置
const rowSpacing = 100; // 行间距(px)
const colSpacing = 50; // 列间距(%)
return {
position: 'absolute',
top: (rowIndex * rowSpacing + 50) + 'px',
left: (colIndex * colSpacing + 25) + '%',
transform: 'translate(-50%, -50%) rotate(-45deg)',
color: 'rgba(0, 0, 0, 0.1)',
backgroundColor: 'transparent',
fontSize: '18px',
fontWeight: 'bold',
opacity: '0.6',
padding: '8px 16px',
whiteSpace: 'nowrap',
pointerEvents: 'none',
userSelect: 'none'
}
}
},
created() {
console.log('[SimpleWatermark] Component created');
console.log('[SimpleWatermark] uni object available:', typeof uni !== 'undefined');
// 立即注册事件监听器
console.log('[SimpleWatermark] Registering event listeners immediately');
// 监听显示水印事件
uni.$on('watermark-show', (content) => {
console.log('[SimpleWatermark] Received watermark-show event with content:', content);
this.watermarkContent = content;
this.showWatermark = true;
console.log('[SimpleWatermark] Watermark state updated - show:', this.showWatermark, 'content:', this.watermarkContent);
});
// 监听隐藏水印事件
uni.$on('watermark-hide', () => {
console.log('[SimpleWatermark] Received watermark-hide event');
this.showWatermark = false;
this.watermarkContent = '';
});
console.log('[SimpleWatermark] Event listeners registered successfully');
// 使用 nextTick 确保DOM完全渲染后再检查水印状态
this.$nextTick(() => {
// 延迟检查当前页面是否需要显示水印
setTimeout(() => {
console.log('[SimpleWatermark] Checking current page watermark status');
const watermarkStore = require('@/store/watermark.js');
if (watermarkStore && watermarkStore.updateWatermark) {
console.log('[SimpleWatermark] Triggering watermark update to sync current state');
watermarkStore.updateWatermark(true);
}
}, 200);
});
},
beforeDestroy() {
// 移除事件监听
uni.$off('watermark-show');
uni.$off('watermark-hide');
console.log('[SimpleWatermark] Event listeners removed');
}
}
</script>
<style scoped>
.watermark-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
z-index: 9999;
overflow: hidden;
}
.watermark-row {
position: relative;
width: 100%;
height: 100px;
}
.watermark-text {
position: absolute;
white-space: nowrap;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
</style>
+20
View File
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>
+323
View File
@@ -0,0 +1,323 @@
{
"common.appName":"MOBILE CRM APP",
"common.userLogin":"User Login",
"common.loginsso":"LOGIN",
"common.loginFail":"Login failed",
"common.playerId":"Player ID",
"common.tier":"Tier",
"common.name":"Name",
"common.gender":"Gender",
"common.property":"Property",
"common.night":"Night",
"common.nights":"Nights",
"common.room":"Room",
"common.rooms":"Rooms",
"common.bookingType":"Booking Type",
"common.misCharge":"Misc Charge",
"common.checkInDate":"C/I Date",
"common.checkOutDate":"C/O Date",
"common.etaTime":"ETA",
"common.roomType":"Room Type",
"common.confirmationNo":"Conf #",
"common.loadMore":"Load more bookings",
"common.loading":"Loading...",
"common.nomore":"No more bookings",
"common.dataNotFound":"Data not found",
"common.cancel":"Cancel",
"common.ok":"OK",
"common.yes":"Yes",
"common.no":"No",
"common.confirm":"Confirm",
"common.in":"IN",
"common.out":"OUT",
"common.start":"START",
"common.end":"END",
"common.selected": "selected",
"common.userLocked":"This user account has been locked",
"common.rangeError":"Date Range invalid",
"common.removeConfirm":"Are you sure to remove?",
"common.warning":"Warning",
"common.login":"Login",
"common.loginAlert":"You haven't logged in yet, please login first",
"common.alterSharerOneself":"Cannot add current player",
"common.alterSharerExist":"Sharer is existing",
"common.alterSharerLimit":"Sharer limit",
"common.saveFail":"Save failed",
"common.connectionFail":"Connect server failed",
"common.errorMsg":"Error Message",
"common.goBack":"Go back",
"common.back":"Back",
"common.language":"Language",
"common.version":"Version",
"common.user":"User",
"common.division":"Division",
"common.department":"Department",
"common.section":"Section",
"common.debugMode":"Debug Mode",
"common.picSaveSuccess":"Image saved",
"common.search":"Search",
"common.status":"Status",
"common.inputRemark":"Please input remark",
"common.nextBooking":"Next booking",
"common.to":"to",
"common.close":"Close",
"common.save":"Save",
"common.inputUserNameAndPassword":"Please input username and password.",
"common.loginerror":"Invalid account or password.",
"common.mfaerror":"Login failed.",
"common.loginfail":"Login failed.",
"common.connected":"Connected",
"common.disconnected":"Disconnected",
"common.submit":"Submit",
"common.noPermission":"No permission to view",
"common.jailBreakTitle":"APP Disabled",
"common.jailBreakMessage":"Devices that have been jailbroken are prohibited from using this app.",
"common.rangeTip": "Date Range invalid",
"common.noRecord":"No Record",
"common.rejectFail":"Reject Approval Routing Fail",
"calendar.mon":"MON",
"calendar.tue":"TUE",
"calendar.wed":"WED",
"calendar.thu":"THU",
"calendar.fri":"FRI",
"calendar.sat":"SAT",
"calendar.sun":"SUN",
"roomCalendar.title":"Calendar",
"roomCalendar.playerTitle":"Player Calendar",
"roomCalendar.updated":"Calendar updated",
"roomCalendar.maxSelectedRoomTypes":"Up to {count} room types can be selected",
"findPlayer.title":"Find Player",
"findPlayer.alert":"Please input player ID",
"findPlayer.noPermission":"You are not authorized to view this player.",
"bookingRecord.title":"Booking Record",
"bookingRecord.calendar":"CALENDAR",
"bookingRecord.newsBooking":"NEW BOOKING / WAITLIST",
"bookingRecord.newsBooking":"ROOM BOOKING",
"bookingRecord.newLimo":"LIMO BOOKING",
"bookingRecord.extend":"Extend",
"bookingRecord.group":"Group",
"bookingRecord.sharer":"Sharer",
"bookingRecord.operaProfile":"No Opera profile, please contact MSC to support.",
"newBooking.title":"New Booking",
"newBooking.multipleDate":"MULTIPLE DATE",
"newBooking.selectDate":"SELECT DATE",
"newBooking.changeBlockAlert":"Are you sure to select this room block?",
"newBooking.room":"Room",
"newBooking.alertRoom":"Room type must be selected",
"newBooking.roomType":"Room Type",
"newBooking.maxNight1":"Maximum",
"newBooking.maxNight2":"consecutive nights",
"newBooking.specialPreference":"Special Preference",
"newBooking.otherProperty":"Other Property",
"newBooking.appFull":"App Channel full on below selected date,please contact MSC team.",
"newBooking.protectionPeriod":"Protection Period on below selected date.",
"newBooking.alertRoomType":"Room type must be selected",
"newBooking.sameBooking":"Player already has a booking on the same day, please contact MSC if required.",
"newBooking.reservedBooking":"Player already has a booking on the same day, booking will put in waitlist.",
"newBooking.waitlist":"The selected date is under Waitlist.",
"newBooking.extendBooking":"Are you sure to make New Booking or Extension?",
"newBooking.alertBookingType":"Booking type must be selected",
"newBooking.extension":"Extension",
"newBooking.preference":"Note:Selected preference is not guaranteed!",
"newBooking.deposit":"Deposit",
"newBooking.postCharge":"Post Charge",
"newBooking.waiveDeposit":"Waive Deposit",
"newBooking.collectDeposit":"Collect Deposit",
"newBooking.yesPost":"Yes Post",
"newBooking.noPost":"No Post",
"newLimo.title":"New Limo",
"newLimo.createTitle":"Create Booking",
"newLimo.editTitle":"Edit Booking",
"newLimo.sectionBookingInformation":"Booking Information",
"newLimo.sectionBookingItinerary":"Booking Itinerary",
"newLimo.sectionApprovalDetails":"Approval Details",
"newLimo.additionalOptions":"Additional Options",
"newLimo.serviceType":"Service Type",
"newLimo.pickUpDate":"Pick-up Date",
"newLimo.pickUpTime":"Pick-up Time",
"newLimo.carType":"Car Type",
"newLimo.noOfPax":"No of Pax",
"newLimo.flightDetail":"Flight Number",
"newLimo.eta":"ETA",
"newLimo.flightStatus":"Flight Status",
"newLimo.pickUpLocation":"Pick-up Location",
"newLimo.greetType":"Greet Type",
"newLimo.signage":"Signage",
"newLimo.dropOffLocation":"Drop-off Location",
"newLimo.bookingContact":"Booking Contact",
"newLimo.phoneNumber":"Phone Number",
"newLimo.highImportance":"High Importance",
"newLimo.tenOut":"10 Out",
"newLimo.tenOutContact":"10 Out Contact",
"newLimo.contactGuestDirectly":"Contact Guest Directly",
"newLimo.guestContact":"Guest Contact",
"newLimo.extraDropOffLocation":"Extra Drop Off Location",
"newLimo.hour":"Hour",
"newLimo.addStop":"+Add",
"newLimo.approvedBy":"Approved By",
"newLimo.paymentMethod":"Payment Method",
"newLimo.tripPrice":"Trip Price",
"newLimo.tripContact":"Trip Contact",
"newLimo.hourlyRate":"Hourly Rate",
"newLimo.remarks":"Remarks",
"newLimo.selectDate":"Select Date",
"newLimo.selectTime":"Select Time",
"newLimo.notApplicable":"N/A",
"newLimo.remarksPlaceholder":"",
"newLimo.removeStop":"Remove",
"bookingConfirm.title":"Preview & Confirm",
"bookingConfirm.submitBooking":"SUBMIT",
"bookingConfirm.createdOn":"Created on",
"bookingConfirm.createdBy":"Created by",
"bookingConfirm.viewBooking":"VIEW BOOKING",
"bookingConfirm.backToRecords":"BACK TO RECORDS",
"bookingConfirm.alert10":"Booking for player ",
"bookingConfirm.alert1":"Booking for player is processing",
"bookingConfirm.alert1_1":"Waitlist for player ",
"bookingConfirm.alert1_2":"Urgent approval for player ",
"bookingConfirm.alert2":" is processing!",
"bookingConfirm.alert3":"Booking Criteria is not qualified!",
"bookingConfirm.alert4":"Select date is in waitlist",
"bookingConfirm.alert5":"Partial Booking Criteria is not qualified!",
"bookingConfirm.IMAlert1":"Please contact MSC for booking",
"bookingConfirm.IMAlert2":"The select date is under waitlist, please seek for approval",
"bookingConfirm.putInWaitlist":"PUT IN WAITLIST",
"bookingConfirm.currentStay":"Current stay",
"bookingConfirm.extending":"Extending",
"bookingConfirm.extensionEmail":"Extending request is proceeding by MSC",
"bookingConfirm.extensionProccessing":"Booking extension is proccessing!",
"bookingConfirm.addSharer":"Add",
"bookingConfirm.canNotAddSharer":"Cannot add sharer",
"bookingConfirm.confirmBooking":"CONFIRM BOOKING",
"bookingConfirm.viewProceedBooking":"VIEW TO PROCEED BOOKING",
"bookingConfirm.wantToWaitList":"Do you want to Waitlist?",
"bookingConfirm.secondRoom1":"Reach maximum room request",
"bookingConfirm.secondRoom2":"One night reach maximum room request",
"bookingConfirm.secondRoom3":"Reserved Suite or above on the same day",
"bookingConfirm.secondRoom4":"Only Standard room is available",
"bookingConfirm.duplicateWaitlist":"Duplicated waitlist is submitted",
"bookingConfirm.remark":"Waitlist Remark",
"bookingConfirm.approvalRemark":"Remark",
"bookingConfirm.urgentApproval":"URGENT APPROVAL REQUEST",
"bookingConfirm.numOfRoom":"Nubmer of Room Request",
"bookingConfirm.requestReason":"Request Reason",
"bookingConfirm.routeToApprover":"Route to Approver",
"bookingConfirm.approvalRoutingRemark":"Approval Routing Remark",
"bookingConfirm.submitApproval":"SUBMIT APPROVAL",
"bookingDetail.title":"Booking Detail",
"bookingDetail.toCancelBooking":"To Cancel Booking?",
"bookingDetail.pendingAlert":"Booking is processing!",
"bookingDetail.waitlistAlert":"Booking is in waitlist!",
"bookingDetail.approvalAlert":"Approval Routing",
"bookingDetail.confirmationNo":"Confirmation No.",
"bookingDetail.saveImage":"SAVE IMAGE",
"bookingDetail.cancelBooking":"CANCEL BOOKING",
"bookingDetail.ETA":"ETA",
"bookingDetail.extension":"EXTENSION",
"bookingDetail.backToBooking":"BACK TO BOOKING",
"bookingDetail.cannotExtend":"Reached booking max stay days",
"bookingDetail.cancelSuccessful":"Booking is Cancelled",
"bookingDetail.cancelFailed":"Booking Cancel failed",
"bookingDetail.errorDate":"Save date must be continuous.",
"bookingDetail.nullDate":"Cancel booking date can not be null",
"bookingDetail.cancelTimeErr":"The current time period cannot cancel the booking.",
"bookingDetail.confirmCancel":"Are you sure to cancel booking?",
"bookingDetail.backToDetail":"Back To Detail",
"bookingDetail.statusChange":"Booking status has changed",
"bookingDetail.approve":"Approve",
"bookingDetail.reject":"Reject",
"bookingDetail.SelectDate":"Select Booking Date",
"bookingDetail.successfully":" Successfully",
"bookingDetail.cannotCancel":"Can not cancel this booking",
"bookingDetail.failed":" Failed",
"bookingDetail.confirmApprove":"Are you sure to approve booking?",
"bookingDetail.confirmReject":"Are you sure to reject booking?",
"bookingDetail.changeMiscChargeSuccess":"Change Misc Charge Success",
"bookingDetail.miscChargeLess":"Amount cannot be less than original.",
"bookingDetail.changeMiscChargeFail":"Change Misc Charge Fail",
"multipleDate.title":"Multiple Date",
"multipleDate.addDate":"ADD DATE",
"multipleDate.pleaseAddDate":"Please Add Date",
"multipleDate.reachMaxBookNum":"Reached multiple book num",
"submitBooking.title":"Submit",
"submitBooking.alert1":"The status of TPD has changed, please check again.",
"submitBooking.submitedSuccessful":"Submitted successfully",
"submitBooking.roomCriteriaNotQualified":"Room Criteria is not qualified",
"submitBooking.underWaitlist":"Under Waitlist",
"submitBooking.copyRemark":"Copy Remark",
"newWaitlist.title":"New Waitlist",
"newWaitlist.remark":"Remark",
"newWaitlist.submitWaitlist":"SUBMIT WAITLIST",
"newWaitlist.savesuccessful":"Save waitlist successful!",
"newWailist.viewSubmitedWaitlist":"VIEW SUBMITED WAITLIST",
"setting.title":"Settings",
"region.title":"Region Restrict",
"region.showMessage":"This app is only available in the Macao region.",
"region.reson":"Reason",
"region.resonMsgNotInMacau":"Your location is not in Macau.",
"region.resonMsgOpenVPN":"Your VPN is ON.",
"region.resonMsgNotInMacauOpenVpn":"Your location is not in Macau and VPN is ON",
"region.resonMsglocationErr":"Error occurred while checking the location.",
"region.resonMsgVPNErr":"Error occurred while checking the VPN.",
"region.resonMsgFunctionErr":"Error occurred while checking the location and VPN.",
"region.retry":"RETRY",
"region.commitTitle":"用戶使用協議及聲明",
"region.commitment1":"本人在此承諾遵守所有適用於使用 Mobile CRM (以下簡稱MCRM) 的公司政策及法定義務。尤其,本人所在地不在澳門特別行政區時,本人同意不使用具有博彩數據的MCRM功能。此外,本人承諾不允許任何其他人(無論是否為澳門美高梅員工)使用安裝在本人移動裝置上的MCRM或存取其中的數據。本人亦承諾不將MCRM上的任何信息分享至其他個人設備。本人知悉此類行為將受到法律的刑事處分,並嚴重違反本人合同規定的責任義務。",
"region.commitment2":"I hereby undertake to adhere to all Company’s policies and all legal obligations that are applicable to the usage of Mobile CRM (hereinafter called MCRM). In particular, I agree not to use MCRM functionality with gaming data whenever my location is outside of the Macau SAR. I further undertake not to allow anybody else, whether an MGM employee or not, to use MCRM on my mobile phone or to access the data therein. I also undertake not to share any of the information on MCRM to any other personal devices. I’m aware that such actions are criminally punished by law and constitute a serious breach of my contractual obligations.",
"region.resonMsgNotInMacauIP":"Your IP is not in Macau.",
"dashboard.title":"Home",
"dashboard.dataAsOf":"Data As Of:",
"dashboard.achievement":"Achievement",
"dashboard.kpi":"KPI",
"dashboard.teamtarget":"Team Target",
"dashboard.individualtarget":"Individual Target",
"dashboard.newreactivetheo":"New & Reactive Theo",
"dashboard.directoffer":"Direct Offer Redemption Rate",
"dashboard.hostedplayer":"Hosted Player Active Rate",
"dashboard.eventattendance":"Event Attendance (w/gaming action)",
"todo.title":"Todo",
"todo.arrival":"Arrival",
"todo.notConfNo":"Record without opera Confirmation No.",
"todo.departure":"Departure",
"todo.inhouse":"Inhouse",
"todo.others":"Others",
"todo.etaSuccess":"CHANGE ETA SUCCESS",
"todo.missParams":"Miss Parameter",
"todo.notRecord":"There are no corresponding other booking records",
"todo.noPermission":"Have not permission",
"todo.invokeError":"Invoke GetTodoDashboard Api Error",
"todo.returnError":"Return Data Error",
"todo.etaFail":"CHANGE ETA FAIL",
"todo.detailFail":"Fetch TodoDetail Fail",
"todo.lookupPlayer":"You have not permission to view this player",
"todo.etaFormatError":"ETA Time Format Error",
"todo.etaRequired": "ETA Time Cannot Null",
"hotel.title":"Room",
"reservations.title":"Reservations",
"approval.title":"Approval",
"hotel.roombooking":"Room Booking",
"approval.pendingApproval":"Pending Approval",
"approval.allRequest":"All Request",
"approval.searchStr":"Search",
"approval.submitApproval":"Confirm to Approval?",
"approval.submitReject":"Confirm to Reject?",
"approval.submitBatchApproval":"Confirm to Batch Approval?",
"approval.batchApprove": "Batch Approve",
"approval.batchReject": "Batch Reject",
"approval.submitBatchReject":"Confirm to Batch Reject?",
"approval.approve":"Approve",
"approval.backToAll":"Back to All Request",
"approval.backToRecord":"Back to Pending Approval",
"approval.reason":"Approval Reason",
"approval.pendingResponse":"Approver",
"bookingConfirm.approvalSuccess": "Approved Successfully.",
"bookingConfirm.approvalFail": "Approved Failed.",
"bookingConfirm.rejectSuccess": "Rejected Successfully.",
"bookingConfirm.failSubmitted": "Submitted Failed.",
"notification.noData":"NO DATA",
"notification.noPermission":"NO PERMISSION",
"notification.pendingApproval":"Pending Approval",
"notification.pendingApprovalRequest": "Pending Approval Request",
"playerDetail.confirm":"CONFIRM",
"newBooking.validEta":"The ETA time format is incorrect. Please re-enter it, eg: HH:mm"
}
+7
View File
@@ -0,0 +1,7 @@
import en from './en.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hant': zhHant,
}
+259
View File
@@ -0,0 +1,259 @@
{
"common.appName": "MOBILE CRM APP",
"common.userLogin": "用戶登入",
"common.loginsso": "登入",
"common.loginFail": "登入失敗",
"common.playerId": "會員號碼",
"common.tier": "等級",
"common.name": "姓名",
"common.gender": "性別",
"common.property": "酒店",
"common.night": "晚",
"common.nights": "晚",
"common.room": "間",
"common.rooms": "間",
"common.bookingType": "預訂類型",
"common.misCharge":"雜項費用",
"common.checkInDate": "入住日期",
"common.checkOutDate": "退房日期",
"common.roomType": "房型",
"common.confirmationNo": "預訂編號",
"common.loadMore": "加載更多",
"common.loading": "正在加載...",
"common.nomore": "沒有更多了",
"common.dataNotFound": "沒有查詢結果",
"common.cancel": "取消",
"common.yes": "確認",
"common.no": "取消",
"common.ok": "確認",
"common.confirm": "確認",
"common.in": "入住",
"common.out": "離開",
"common.start":"開始",
"common.selected": "已選擇",
"common.userLocked":"這個用戶賬戶已鎖定",
"common.ipLocked":"這個IP已鎖定",
"common.end":"終止",
"common.rangeError":"日期範圍不正確",
"common.removeConfirm": "確認要刪除嗎?",
"common.warning": "系統提示",
"common.login": "登入",
"common.loginAlert": "您還沒有登入,請先登入",
"common.saveFail": "保存失敗",
"common.connectionFail": "無法連接伺服器",
"common.alterSharerOneself": "不能添加當前客人",
"common.alterSharerExist": "該客人已添加",
"common.alterSharerLimit": "同住人限制",
"common.errorMsg": "錯誤信息",
"common.goBack": "返回",
"common.back":"返回",
"common.language": "語言",
"common.version": "版本",
"common.user": "用戶",
"common.division": "分部",
"common.department": "部門",
"common.section": "組別",
"common.debugMode": "調試模式",
"common.picSaveSuccess": "截屏已保存",
"common.search": "查詢",
"common.status": "狀態",
"common.inputRemark": "請輸入備註",
"common.nextBooking":"下一個預訂",
"common.to": "到",
"common.close":"關閉",
"common.save":"保存",
"common.inputUserNameAndPassword": "請輸入用戶名和密碼",
"common.loginerror":"用戶名或密碼錯誤",
"common.mfaerror":"登入失敗",
"common.loginfail":"登入失敗",
"common.connected":"已連接",
"common.disconnected":"連接失敗",
"common.submit":"遞交",
"common.noPermission":"您沒有權限查看",
"common.rangeTip":"日期范围无效",
"common.jailBreakTitle":"禁止使用",
"common.jailBreakMessage":"禁止越獄過的設備使用該APP",
"common.noRecord":"沒有記錄",
"common.etaTime":"預計時間",
"calendar.mon": "一",
"calendar.tue": "二",
"calendar.wed": "三",
"calendar.thu": "四",
"calendar.fri": "五",
"calendar.sat": "六",
"calendar.sun": "日",
"findPlayer.title": "查找客人",
"findPlayer.alert": "請輸入客人ID",
"findPlayer.noPermission": "您沒有權限查看此客人.",
"bookingRecord.title": "預定記錄",
"bookingRecord.newsBooking": "預訂房間 / 候補名單",
"bookingRecord.extend": "續房",
"bookingRecord.group": "關聯",
"bookingRecord.sharer": "同住人",
"bookingRecord.operaProfile": "沒有Opera profile, 請聯係MSC幫助.",
"newBooking.title": "預訂房間",
"newBooking.multipleDate": "多組日期",
"newBooking.selectDate": "選擇日期",
"newBooking.changeBlockAlert": "您確認切換到該block嗎?",
"newBooking.room": "房",
"newBooking.alertRoom": "必須選擇房型",
"newBooking.roomType": "房型",
"newBooking.maxNight1": "選擇天數不能超過",
"newBooking.maxNight2": "天",
"newBooking.specialPreference": "特殊需求",
"newBooking.otherProperty": "其他酒店",
"newBooking.appFull": "以下日期房間已滿,請聯係MSC team.",
"newBooking.protectionPeriod": "以下日期為保護期間.",
"newBooking.alertRoomType": "必須選擇房型",
"newBooking.sameBooking": "客人相同日期已有預定,如有必要請聯係MSC",
"newBooking.reservedBooking": "客人相同日期已有預定,確認將放入候補名單",
"newBooking.waitlist": "選擇的日期要放入候補名單.",
"newBooking.extendBooking": "您確定要預訂還是續房?",
"newBooking.alertBookingType": "必須選擇預訂類型",
"newBooking.extension": "續房",
"newBooking.preference": "注意:特殊需求均無法保證,須視乎實際状況安排",
"newBooking.deposit":"押金",
"newBooking.postCharge":"房賬",
"newBooking.waiveDeposit":"免收押金",
"newBooking.collectDeposit":"收取押金",
"newBooking.yesPost":"掛房賬",
"newBooking.noPost":"鎖房賬",
"bookingConfirm.title": "預覽 & 確認",
"bookingConfirm.submitBooking": "遞交預定",
"bookingConfirm.createdOn": "預訂日期",
"bookingConfirm.createdBy": "預訂者",
"bookingConfirm.viewBooking": "預定詳情",
"bookingConfirm.urgentApproval":"緊急審批請求",
"bookingConfirm.submitApproval":"提交審批人",
"bookingConfirm.alert10": "正在處理客人 ",
"bookingConfirm.alert1": "預訂正在處理中",
"bookingConfirm.alert1_1":" 的候補名單!",
"bookingConfirm.alert2": " 的預定!",
"bookingConfirm.alert3": "您的預定未能通過!",
"bookingConfirm.alert4": "需放在候補名單",
"bookingConfirm.alert5": "部分預定未能通過!",
"bookingConfirm.IMAlert1":"請聯繫MSC預訂房間",
"bookingConfirm.IMAlert2":"選擇的日期需放在候補名單, 請申請批准預訂房間",
"bookingConfirm.putInWaitlist": "放入候補名單",
"bookingConfirm.currentStay": "當前入住",
"bookingConfirm.extending": "延長入住",
"bookingConfirm.extensionEmail": "MSC正在處理續房",
"bookingConfirm.extensionProccessing": "續房正在處理中",
"bookingConfirm.addSharer": "新增",
"bookingConfirm.canNotAddSharer": "不能新增同住人",
"bookingConfirm.confirmBooking": "確認預定",
"bookingConfirm.backToRecords": "返回主頁",
"bookingConfirm.viewProceedBooking": "查看並繼續",
"bookingConfirm.wantToWaitList": "是否放入候補名單?",
"bookingConfirm.secondRoom1":"超過可預訂房間數量",
"bookingConfirm.secondRoom2":"其中一晚已超過可預訂房間數量",
"bookingConfirm.secondRoom3":"已預訂套房或以上房型",
"bookingConfirm.secondRoom4":"只可預訂基本房型",
"bookingConfirm.duplicateWaitlist":"已提交候補名單",
"bookingConfirm.remark":"候補名單備註",
"bookingConfirm.numOfRoom":"請求房間數量",
"bookingConfirm.requestReason":"請求原因",
"bookingConfirm.routeToApprover":"發送至審批員",
"bookingConfirm.approvalRoutingRemark":"審批備注",
"bookingDetail.title": "預定詳情",
"bookingDetail.pendingAlert": "預定正在處理中!",
"bookingDetail.waitlistAlert": "預定已列入候補名單!",
"bookingDetail.confirmationNo": "預訂編號",
"bookingDetail.saveImage": "保存圖片",
"bookingDetail.extension": "續房",
"bookingDetail.cancelSuccessful": "取消成功",
"bookingDetail.cancelFailed": "取消失敗",
"bookingDetail.confirmCancel": "你確定要取消預定嗎?",
"bookingDetail.statusChange": "預定狀態已改變",
"bookingDetail.approve":"審批",
"bookingDetail.reject":"拒絕",
"bookingDetail.changeMiscChargeSuccess":"修改雜項費用成功",
"bookingDetail.changeMiscChargeFail":"修改雜項費用失敗",
"bookingDetail.cancelTimeErr":"當前時間段不能取消預定",
"bookingDetail.successfully":"成功",
"bookingDetail.failed":"失敗",
"bookingDetail.toCancelBooking": "確定要取消預訂嗎?",
"bookingDetail.backToBooking": "返回預訂",
"bookingDetail.backToDetail": "返回詳情",
"bookingDetail.SelectDate": "選擇預訂日期",
"bookingDetail.confirmApprove": "確定要批准此預訂嗎?",
"bookingDetail.confirmReject": "確定要拒絕此預訂嗎?",
"bookingDetail.errorDate":"必須選擇連續的日期!",
"bookingDetail.cancelBooking":"取消預定",
"bookingDetail.ETA":"預計時間",
"bookingDetail.miscChargeLess":"金額不可低於原值.",
"bookingDetail.cannotCancel":"不能取消这条记录",
"multipleDate.title": "選擇多個日期",
"multipleDate.addDate": "新增日期",
"multipleDate.pleaseAddDate": "請新增日期",
"multipleDate.reachMaxBookNum": "已達最大多個日期預定",
"submitBooking.title": "遞交",
"submitBooking.alert1": "TPD的狀態發生了改變,請重新選擇",
"submitBooking.submitedSuccessful": "遞交成功",
"submitBooking.roomCriteriaNotQualified":"不符合訂房條件",
"submitBooking.underWaitlist":"放入候補名單",
"submitBooking.copyRemark":"複製備註",
"putInWaitlist.title": "候補名單",
"newWaitlist.title": "创建候補名單",
"newWaitlist.remark": "備註",
"newWaitlist.submitWaitlist": "遞交候補名單",
"newWaitlist.savesuccessful": "成功遞交候補名單!",
"newWaitlist.viewSubmitedWaitlist": "查看候補名單",
"setting.title": "設定",
"region.title":"地區限制",
"region.showMessage":"此應用程序僅限於澳門使用。",
"region.reson":"禁用原因",
"region.resonMsgNotInMacau":"您的定位不在澳門",
"region.resonMsgOpenVPN":"您打開了VPN",
"region.resonMsgNotInMacauOpenVpn":"您的定位不在澳門且打開了VPN",
"region.resonMsglocationErr":"檢查定位時出錯",
"region.resonMsgVPNErr":"檢查VPN時出錯",
"region.resonMsgFunctionErr":"檢查定位和VPN時出錯",
"region.retry":"重試",
"region.commitTitle":"用戶使用協議及聲明",
"region.commitment1":"本人在此承諾遵守所有適用於使用 Mobile CRM (以下簡稱MCRM) 的公司政策及法定義務。尤其,本人所在地不在澳門特別行政區時,本人同意不使用具有博彩數據的MCRM功能。此外,本人承諾不允許任何其他人(無論是否為澳門美高梅員工)使用安裝在本人移動裝置上的MCRM或存取其中的數據。本人亦承諾不將MCRM上的任何信息分享至其他個人設備。本人知悉此類行為將受到法律的刑事處分,並嚴重違反本人合同規定的責任義務。",
"region.commitment2":"I hereby undertake to adhere to all Company’s policies and all legal obligations that are applicable to the usage of Mobile CRM (hereinafter called MCRM). In particular, I agree not to use MCRM functionality with gaming data whenever my location is outside of the Macau SAR. I further undertake not to allow anybody else, whether an MGM employee or not, to use MCRM on my mobile phone or to access the data therein. I also undertake not to share any of the information on MCRM to any other personal devices. I’m aware that such actions are criminally punished by law and constitute a serious breach of my contractual obligations.",
"region.resonMsgNotInMacauIP":"您的IP不在澳門",
"dashboard.title":"主頁",
"dashboard.dataAsOf":"數據更新於:",
"dashboard.achievement":"成就",
"dashboard.kpi":"指標",
"dashboard.teamtarget":"團隊目標",
"dashboard.individualtarget":"個人目標",
"dashboard.newreactivetheo":"New & Reactive Theo",
"dashboard.directoffer":"Direct Offer Redemption Rate",
"dashboard.hostedplayer":"Hosted Player Active Rate",
"dashboard.eventattendance":"Event Attendance (w/gaming action)",
"todo.title":"待辦",
"todo.arrival":"到達",
"todo.departure":"離開",
"todo.inhouse":"在場",
"todo.others":"其他",
"todo.notConfNo":"該條記錄沒有Opera Confirmation No.",
"todo.etaSuccess":"修改ETA成功",
"todo.etaFail":"修改ETA失敗",
"todo.detailFail":"獲取信息失敗",
"todo.missParams":"缺少參數",
"todo.notRecord":"沒有對應的記錄",
"todo.invokeError":"調用ESB API時出錯",
"todo.noPermission":"沒有權限",
"todo.returnError":"返回數據時出錯",
"todo.etaFormatError":"ETA Time格式錯誤",
"todo.etaRequired": "ETA Time不能為空",
"todo.lookupPlayer":"您沒有權限查看該玩家",
"hotel.title":"酒店",
"approval.approve": "批准",
"hotel.roombooking":"酒店預定",
"approval.pendingApproval":"等待審批",
"approval.batchApprove": "批量批准",
"approval.batchReject": "批量拒絕",
"approval.approvalFail": "審批失敗",
"approval.allRequest":"所有請求",
"approval.searchStr":"搜索",
"notification.noData":"沒有返回數據",
"notification.noPermission":"沒有權限",
"notification.pendingApproval":"審批列表",
"notification.pendingApprovalRequest": "待批准請求",
"playerDetail.confirm":"確認",
"newBooking.validEta":"ETA 時間格式有誤,請重新輸入 eg: HH:mm"
}
+122
View File
@@ -0,0 +1,122 @@
import App from './App'
import uView from '@/uni_modules/uview-ui'
import store from './store'
import messages from './locale/index'
import watermark from './store/watermark.js'
let i18nConfig = {
locale: uni.getLocale(),
messages
}
// #ifndef VUE3
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import './uni.promisify.adaptor'
Vue.use(VueI18n)
const i18n = new VueI18n(i18nConfig)
Vue.use(watermark, {
loginPaths: [
'./salessupport/todoList/todoList.vue'
],
defaultContent: 'Cannot get user data'
});
Vue.config.productionTip = false
Vue.prototype.$store = store
// 注册全局方法
Vue.prototype.isLogin = function(){
getApp().isLogin();
}
Vue.prototype.checkJailbreak = function(){
getApp().checkJailbreak();
}
Vue.prototype.navBack = function(delta){
getApp().navBack(delta);
}
Vue.prototype.navTo = function(url,type,auth){
getApp().navTo(url,type,auth);
}
Vue.prototype.writeLog = function(userId,eventCode,transactionId,description,requestBody,responseBody,successTag,debugTag){
getApp().writeLog(userId,eventCode,transactionId,description,requestBody,responseBody,successTag,debugTag);
}
Vue.prototype.redirectByPermission = function(userData,needRedirect){
getApp().redirectByPermission(userData,needRedirect);
}
Vue.prototype.showTabbarByPermission = function(userData){
getApp().showTabbarByPermission(userData);
}
Vue.prototype.checkInMacau = function(){
return getApp().checkInMacau();
}
Vue.prototype.checkVPNOpen = function(){
return getApp().checkVPNOpen();
}
Vue.prototype.checkLocationAndVPN = function(type){
return getApp().checkLocationAndVPN(type);
}
Vue.prototype.logout = function(){
return getApp().logout();
}
Vue.prototype.$onLaunched = new Promise((resolve, reject) => {
Vue.prototype.$isResolve = resolve
})
App.mpType = 'app'
/*uni.addInterceptor('request', {
success: function(request) {
let adfsCookie = uni.getStorageSync('adfs_cookie');
console.log('Set request Cookie');
if (adfsCookie) {
console.log(adfsCookie);*/
/*var cookies ="FederationAuthCookie="+ adfsCookie+
";RequestedSecurityToken="+ adfsCookie+
";FedAuth="+adfsCookie;*/
//request.header.Cookie = adfsCookie; // 将每次的请求头中加入Cookies
//request.header.cookie = cookies;
//request.header.FederationAuthCookie=adfsCookie;
//request.header.RequestedSecurityToken=adfsCookie;
//request.header.FedAuth=adfsCookie;
/*request.header.Authorization='Bearer '+adfsCookie;
}
}
});*/
const app = new Vue({
i18n,
store,
...App
})
// 引入请求封装,将app参数传递到配置中
require('@/common/request.js')(app)
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
import { createI18n } from 'vue-i18n'
const i18n = createI18n(i18nConfig)
export function createApp() {
const app = createSSRApp(App)
/*uni.addInterceptor('request', {
success: function(request) {
let adfsCookie = uni.getStorageSync('adfs_cookie');
console.log('Set request Cookie');
if (adfsCookie) {
var cookies ={
FederationAuthCookie: adfsCookie,
RequestedSecurityToken: adfsCookie
};
request.header.Cookies = cookies // 将每次的请求头中加入Cookies
}
}
});*/
app.use(i18n)
return {
app
}
}
// #endif
+166
View File
@@ -0,0 +1,166 @@
{
"name" : "MobileCRM",
"appid" : "__UNI__A500790",
"description" : "",
"versionName" : "1.6.1",
"versionCode" : 161,
"transformPx" : false,
"app-plus" : {
"usingComponents" : true,
"nvueStyleCompiler" : "uni-app",
"compilerVersion" : 3,
"splashscreen" : {
"alwaysShowBeforeRender" : true,
"waiting" : true,
"autoclose" : true,
"delay" : 0
},
"modules" : {
"Camera" : {},
"UTS-Proxy" : {},
"Geolocation" : {}
},
"distribute" : {
"distribute" : {
"orientation" : [ "portrait" ]
},
"android" : {
"permissions" : [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
"ios" : {
"dSYMs" : false,
"capabilities" : {
"entitlements" : {
"com.apple.developer.networking.networkextension" : [ "packet-tunnel-provider", "app-proxy-provider" ],
"com.apple.developer.networking.vpn.api" : "allow-vpn"
}
},
"privacyDescription" : {
"NSPhotoLibraryUsageDescription" : "",
"NSPhotoLibraryAddUsageDescription" : "",
"NSLocationWhenInUseUsageDescription" : "需要您的位置权限以提供附近服务",
"NSLocationAlwaysAndWhenInUseUsageDescription" : "需要您的位置权限以提供附近服务",
"NSLocationAlwaysUsageDescription" : "需要您的位置权限以提供附近服务",
"NSNetworkVolumesUsageDescription" : "应用需要访问网络信息以检测VPN状态",
"NSLocalNetworkUsageDescription" : "应用需要访问本地网络以检测VPN连接",
"NSNetworkExtensionUsageDescription" : "此应用需要访问网络扩展以检测VPN连接状态"
},
"permissions" : {
"location" : {
"description" : "该应用需要获取位置信息以便于定位功能"
}
},
"urltypes" : "mcrm.com.mgm.mcrm"
},
"sdkConfigs" : {
"ad" : {},
"oauth" : {},
"geolocation" : {
"system" : {
"__platform__" : [ "ios" ]
}
}
},
"icons" : {
"ios" : {
"appstore" : "",
"iphone" : {
"app@2x" : "",
"app@3x" : "",
"notification@2x" : "",
"notification@3x" : "",
"settings@2x" : "",
"settings@3x" : "",
"spotlight@2x" : "",
"spotlight@3x" : ""
},
"ipad" : {
"app" : "",
"app@2x" : "",
"notification" : "",
"notification@2x" : "",
"proapp@2x" : "",
"settings" : "",
"settings@2x" : "",
"spotlight" : "",
"spotlight@2x" : ""
}
},
"android" : {
"hdpi" : "",
"xhdpi" : "",
"xxhdpi" : "",
"xxxhdpi" : ""
}
},
"splashscreen" : {
"iosStyle" : "storyboard",
"ios" : {
"storyboard" : "/Users/liuchong/Downloads/MCRMStoryboard.zip"
}
}
},
"nativePlugins" : {
"NetworkUtils" : {
"__plugin_info__" : {
"name" : "NetworkUtilsModule",
"description" : "For network",
"platforms" : "iOS",
"url" : "",
"android_package_name" : "",
"ios_bundle_id" : "",
"isCloud" : false,
"bought" : -1,
"pid" : "",
"parameters" : {}
}
}
}
},
"quickapp" : {},
"mp-weixin" : {
"appid" : "",
"setting" : {
"urlCheck" : false
},
"usingComponents" : true
},
"mp-alipay" : {
"usingComponents" : true
},
"mp-baidu" : {
"usingComponents" : true
},
"mp-toutiao" : {
"usingComponents" : true
},
"uniStatistics" : {
"enable" : false
},
"vueVersion" : "2",
"locale" : "en",
"h5" : {
"devServer" : {
"https" : false
},
"router" : {
"base" : "/mcrm_mobile_app"
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "NetworkUtilsModule",
"id": "NetworkUtils",
"version": "1.0.0",
"description": "For network",
"_dp_type": "nativeplugin",
"_dp_nativeplugin": {
"ios": {
"plugins": [{
"type": "module",
"name": "NetworkUtils-NetworkUtilsModule",
"class": "NetworkUtilsModule"
}],
"integrateType": "framework",
"deploymentTarget": "12.0"
}
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"name": "checkbox",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/crypto-js": {
"version": "4.2.0",
"resolved": "https://registry.npmmirror.com/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT"
}
}
}
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+607
View File
@@ -0,0 +1,607 @@
# noble-ciphers
Audited & minimal JS implementation of Salsa20, ChaCha and AES.
- 🔒 [**Audited**](#security) by an independent security firm
- 🔻 Tree-shakeable: unused code is excluded from your builds
- 🏎 Fast: hand-optimized for caveats of JS engines
- 🔍 Reliable: property-based / cross-library / wycheproof tests ensure correctness
- 💼 AES: ECB, CBC, CTR, CFB, GCM, SIV (nonce misuse-resistant), AESKW, AESKWP
- 💃 Salsa20, ChaCha, XSalsa20, XChaCha, ChaCha8, ChaCha12, Poly1305
- 🥈 Two AES implementations: pure JS or friendly WebCrypto wrapper
- 🪶 11KB (gzipped) for everything, 3KB for ChaCha-only build
Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative. Check out [Upgrading](#upgrading) for information about upgrading from previous versions.
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-ciphers/discussions) for questions and support.
### This library belongs to _noble_ cryptography
> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
- Zero or minimal dependencies
- Highly readable TypeScript / JS code
- PGP-signed releases and transparent NPM builds
- All libraries:
[ciphers](https://github.com/paulmillr/noble-ciphers),
[curves](https://github.com/paulmillr/noble-curves),
[hashes](https://github.com/paulmillr/noble-hashes),
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
[ed25519](https://github.com/paulmillr/noble-ed25519)
- [Check out the homepage](https://paulmillr.com/noble/)
for reading resources, documentation, and apps built with noble
## Usage
> `npm install @noble/ciphers`
> `deno add jsr:@noble/ciphers`
We support all major platforms and runtimes.
For React Native, you may need a
[polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).
A standalone file
[noble-ciphers.js](https://github.com/paulmillr/noble-ciphers/releases) is also available.
```ts
// import * from '@noble/ciphers'; // Error: use sub-imports, to ensure small app size
import { gcm, gcmsiv } from '@noble/ciphers/aes.js';
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
// Unauthenticated encryption: make sure to use HMAC or similar
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
import { aeskw, aeskwp } from '@noble/ciphers/aes.js'; // KW
import { bytesToHex, hexToBytes, managedNonce, randomBytes } from '@noble/ciphers/utils.js';
```
- [Examples](#examples)
- [XChaCha20-Poly1305 encryption](#xchacha20-poly1305-encryption)
- [AES-256-GCM encryption](#aes-256-gcm-encryption)
- [managedNonce: automatic nonce handling](#managednonce-automatic-nonce-handling)
- [AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw](#aes-gcm-siv-ctr-cfb-cbc-ecb-aeskw)
- [AES: friendly WebCrypto wrapper](#aes-friendly-webcrypto-wrapper)
- [Reuse array for input and output](#reuse-array-for-input-and-output)
- [Use password for encryption](#use-password-for-encryption)
- [Internals](#internals)
- [Picking a cipher](#picking-a-cipher)
- [How to encrypt properly](#how-to-encrypt-properly)
- [Nonces](#nonces)
- [Encryption limits](#encryption-limits)
- [AES block modes](#aes-block-modes)
- [Implemented primitives](#implemented-primitives)
- [Security](#security)
- [Speed](#speed)
- [Upgrading](#upgrading)
- [Contributing & testing](#contributing--testing)
- [License](#license)
## Examples
> [!NOTE]
> Use different nonce every time `encrypt()` is done.
#### XChaCha20-Poly1305 encryption
```js
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
import { randomBytes } from '@noble/ciphers/utils.js';
const key = randomBytes(32); // random key
// const key = new Uint8Array([ // existing key
// 169, 88, 160, 139, 168, 29, 147, 196, 14, 88, 237, 76, 243, 177, 109, 140,
// 195, 140, 80, 10, 216, 134, 215, 71, 191, 48, 20, 104, 189, 37, 38, 55,
// ]);
// import { hexToBytes } from '@noble/ciphers/utils.js'; // hex key
// const key = hexToBytes('4b7f89bac90a1086fef73f5da2cbe93b2fae9dfbf7678ae1f3e75fd118ddf999');
const nonce = randomBytes(24);
const chacha = xchacha20poly1305(key, nonce);
const data = new TextEncoder().encode('hello noble');
const ciphertext = chacha.encrypt(data);
const data_ = chacha.decrypt(ciphertext); // new TextDecoder().decode(data_) === data
```
#### AES-256-GCM encryption
```js
import { gcm } from '@noble/ciphers/aes.js';
import { randomBytes } from '@noble/ciphers/utils.js';
const key = randomBytes(32);
const nonce = randomBytes(24);
const data = new TextEncoder().encode('hello noble');
const aes = gcm(key, nonce);
const ciphertext = aes.encrypt(data);
const data_ = aes.decrypt(ciphertext); // new TextDecoder().decode(data_) === data
```
#### managedNonce: automatic nonce handling
We provide API that manages nonce internally instead of exposing them to library's user.
For `encrypt`: a `nonceBytes`-length buffer is fetched from CSPRNG and prenended to encrypted ciphertext.
For `decrypt`: first `nonceBytes` of ciphertext are treated as nonce.
> [!NOTE]
> AES-GCM & ChaCha (NOT XChaCha) [limit amount of messages](#encryption-limits)
> encryptable under the same key.
```js
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
import { hexToBytes, managedNonce } from '@noble/ciphers/utils.js';
const key = hexToBytes('fa686bfdffd3758f6377abbc23bf3d9bdc1a0dda4a6e7f8dbdd579fa1ff6d7e1');
const chacha = managedNonce(xchacha20poly1305)(key); // manages nonces for you
const data = new TextEncoder().encode('hello noble');
const ciphertext = chacha.encrypt(data);
const data_ = chacha.decrypt(ciphertext);
```
#### AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw
```js
import { gcm, gcmsiv, aessiv, ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
import { randomBytes } from '@noble/ciphers/utils.js';
const plaintext = new Uint8Array(32).fill(16);
for (let cipher of [gcm, gcmsiv, aessiv]) {
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
const nonce = randomBytes(12);
const ciphertext_ = cipher(key, nonce).encrypt(plaintext);
const plaintext_ = cipher(key, nonce).decrypt(ciphertext_);
}
for (const cipher of [ctr, cbc, cfb]) {
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
const nonce = randomBytes(16);
const ciphertext_ = cipher(key, nonce).encrypt(plaintext);
const plaintext_ = cipher(key, nonce).decrypt(ciphertext_);
}
for (const cipher of [ecb]) {
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
const ciphertext_ = cipher(key).encrypt(plaintext);
const plaintext_ = cipher(key).decrypt(ciphertext_);
}
// AESKW, AESKWP
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
import { hexToBytes } from '@noble/ciphers/utils.js';
const kek = hexToBytes('000102030405060708090A0B0C0D0E0F');
const keyData = hexToBytes('00112233445566778899AABBCCDDEEFF');
const ciphertext = aeskw(kek).encrypt(keyData);
```
#### AES: friendly WebCrypto wrapper
Noble implements AES. Sometimes people want to use built-in `crypto.subtle` instead. However, it has terrible API. We simplify access to built-ins.
> [!NOTE]
> Webcrypto methods are always async.
```js
import { gcm, ctr, cbc } from '@noble/ciphers/webcrypto.js';
import { randomBytes } from '@noble/ciphers/utils.js';
const plaintext = new Uint8Array(32).fill(16);
const key = randomBytes(32);
for (const cipher of [gcm]) {
const nonce = randomBytes(12);
const ciphertext_ = await cipher(key, nonce).encrypt(plaintext);
const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_);
}
for (const cipher of [ctr, cbc]) {
const nonce = randomBytes(16);
const ciphertext_ = await cipher(key, nonce).encrypt(plaintext);
const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_);
}
```
#### Reuse array for input and output
To avoid additional allocations, Uint8Array can be reused
between encryption and decryption calls.
> [!NOTE]
> Some ciphers don't support unaligned (`byteOffset % 4 !== 0`) Uint8Array as
> destination. It can decrease performance, making the optimization pointless.
```js
import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
import { randomBytes } from '@noble/ciphers/utils.js';
const key = randomBytes(32);
const nonce = randomBytes(12);
const chacha = chacha20poly1305(key, nonce);
const input = new TextEncoder().encode('hello noble'); // length == 12
const inputLength = input.length;
const tagLength = 16;
const buf = new Uint8Array(inputLength + tagLength);
const start = buf.subarray(0, inputLength);
start.set(input); // copy input to buf
chacha.encrypt(start, buf); // encrypt into `buf`
chacha.decrypt(buf, start); // decrypt into `start`
```
xsalsa20poly1305 also supports this, but requires 32 additional bytes for encryption / decryption,
due to its inner workings.
#### Randomness generation
We provide userspace CSPRNG (cryptographically secure pseudorandom number generator).
It's best to limit their usage to non-production, non-critical cases: for example, test-only usage.
ChaCha-based CSPRNG does not have a specification as per 2025, which makes it less secure.
```js
import { randomBytes } from '@noble/ciphers/utils.js';
import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';
import { rngChacha8, rngChacha20 } from '@noble/ciphers/chacha.js';
// 1. Best: WebCrypto
const rnd1 = randomBytes(32);
// 2. AES-CTR DRBG
const seed2 = randomBytes(48);
const rnd2 = rngAesCtrDrbg256(seed2).randomBytes(1024);
// 3. ChaCha8 CSPRNG
const seed3 = randomBytes(32);
const rnd3 = rngChacha8(seed3).randomBytes(1024);
```
#### Use password for encryption
It is not safe to convert password into Uint8Array.
Instead, KDF stretching function like PBKDF2 / Scrypt / Argon2id
should be applied to convert password to AES key.
Make sure to use salt (app-specific secret) in addition to password.
> `npm install @noble/hashes`
```js
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
import { managedNonce } from '@noble/ciphers/utils.js';
import { scrypt } from '@noble/hashes/scrypt.js';
// Convert password into 32-byte key using scrypt
const PASSWORD = 'correct-horse-battery-staple';
const APP_SPECIFIC_SECRET = 'salt-12345678-secret';
const SECURITY_LEVEL = 2 ** 20; // requires 1GB of RAM to calculate
// sync, but scryptAsync is also available
const key = scrypt(PASSWORD, APP_SPECIFIC_SECRET, { N: SECURITY_LEVEL, r: 8, p: 1, dkLen: 32 });
// Use random, managed nonce
const chacha = managedNonce(xchacha20poly1305)(key);
const data = new TextEncoder().encode('hello noble');
const ciphertext = chacha.encrypt(data);
const data_ = chacha.decrypt(ciphertext);
```
## Internals
### Picking a cipher
We suggest to use **XChaCha20-Poly1305** because it's very fast and allows random keys.
**AES-GCM-SIV** is also a good idea, because it provides resistance against nonce reuse.
**AES-GCM** is a good option when those two are not available.
### How to encrypt properly
- Use unpredictable key with enough entropy
- Random key must be using cryptographically secure random number generator (CSPRNG), not `Math.random` etc.
- Non-random key generated from KDF is fine
- Re-using key is fine, but be aware of rules for cryptographic key wear-out and [encryption limits](#encryption-limits)
- Use new nonce every time and [don't repeat it](#nonces)
- chacha and salsa20 are fine for sequential counters that _never_ repeat: `01, 02...`
- xchacha and xsalsa20 can use random nonces instead
- AES-GCM should use 12-byte nonces: smaller nonces are security risk
- Prefer authenticated encryption (AEAD)
- Good: chacha20poly1305, GCM, GCM-SIV, ChaCha+HMAC, CTR+HMAC, CBC+HMAC
- Bad: chacha20, raw CTR, raw CBC
- Flipping bits or ciphertext substitution won't be detected in unauthenticated ciphers
- Polynomial MACs are not perfect for every situation:
they lack Random Key Robustness: the MAC can be forged, and can't
be used in PAKE schemes. See
[invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
To combat salamanders, `hash(key)` can be included in ciphertext,
however, this would violate ciphertext indistinguishability:
an attacker would know which key was used - so `HKDF(key, i)`
could be used instead.
- Don't re-use keys between different protocols
- For example, using ECDH key in AES can be bad
- Use hkdf or, at least, a hash function to create sub-key instead
### Nonces
Most ciphers need a key and a nonce (aka initialization vector / IV) to encrypt a data.
Repeating (key, nonce) pair with different plaintexts would allow an attacker to decrypt it.
ciphertext_a = encrypt(plaintext_a, key, nonce)
ciphertext_b = encrypt(plaintext_b, key, nonce)
stream_diff = xor(ciphertext_a, ciphertext_b) # Break encryption
One way of not repeating nonces is using counters:
for i in 0..:
ciphertext[i] = encrypt(plaintexts[i], key, i)
Another is generating random nonce every time:
for i in 0..:
rand_nonces[i] = random()
ciphertext[i] = encrypt(plaintexts[i], key, rand_nonces[i])
- Counters are OK, but it's not always possible to store current counter value:
e.g. in decentralized, unsyncable systems.
- Randomness is OK, but there's a catch:
ChaCha20 and AES-GCM use 96-bit / 12-byte nonces, which implies higher chance of collision.
In the example above, `random()` can collide and produce repeating nonce.
Chance is even higher for 64-bit nonces, which GCM allows - don't use them.
- To safely use random nonces, utilize XSalsa20 or XChaCha:
they increased nonce length to 192-bit, minimizing a chance of collision.
AES-SIV is also fine. In situations where you can't use eXtended-nonce
algorithms, key rotation is advised. hkdf would work great for this case.
### Encryption limits
A "protected message" would mean a probability of `2**-50` that a passive attacker
successfully distinguishes the ciphertext outputs of the AEAD scheme from the outputs
of a random function.
- Max message size:
- AES-GCM: ~68GB, `2**36-256`
- Salsa, ChaCha, XSalsa, XChaCha: ~256GB, `2**38-64`
- Max amount of protected messages, under same key:
- AES-GCM: `2**32.5`
- Salsa, ChaCha: `2**46`, but only integrity (MAC) is affected, not confidentiality (encryption)
- XSalsa, XChaCha: `2**72`
- Max amount of protected messages, across all keys:
- AES-GCM: `2**69/B` where B is max blocks encrypted by a key. Meaning
`2**59` for 1KB, `2**49` for 1MB, `2**39` for 1GB
- Salsa, ChaCha, XSalsa, XChaCha: `2**100`
- Max amount of protected messages, under same key, using **random nonce**:
- Relevant for 12-byte nonces with `managedNonce`: AES-GCM, ChaCha
- `2**23` (8M) messages for `2**-50` chance, `2**32.5` (4B) for `2**-32.5` chance
Check out [draft-irtf-cfrg-aead-limits](https://datatracker.ietf.org/doc/draft-irtf-cfrg-aead-limits/) for details.
### Implemented primitives
- Salsa20 stream cipher, released in 2005.
Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
which are hard to implement in a constant-time manner.
Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
- [XSalsa20](https://cr.yp.to/snuffle/xsalsa-20110204.pdf), extended-nonce
variant was released in 2008. It switched nonces from 96-bit to 192-bit,
and became safe to be picked at random.
- Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
We provide the alias and corresponding seal / open methods.
"crypto_box" and "sealedbox" are available in package [noble-sodium](https://github.com/serenity-kit/noble-sodium).
- Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf)
and [website](https://cr.yp.to/snuffle.html).
- ChaCha20 stream cipher, released in 2008. Developed after Salsa20,
ChaCha aims to increase diffusion per round.
- [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)
extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
randomly-generated nonces.
- Check out
[RFC 8439](https://www.rfc-editor.org/rfc/rfc8439),
[PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and
[website](https://cr.yp.to/chacha.html).
- AES is a variant of Rijndael block cipher, standardized by NIST in 2001.
We provide the fastest available pure JS implementation.
- We support AES-128, AES-192 and AES-256: the mode is selected dynamically,
based on key length (16, 24, 32).
- AES-GCM-SIV nonce-misuse-resistant mode is also provided. Our implementation of SIV
has the same speed as GCM: there is no performance hit.
The mode is described in [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452).
- There is a separate AES-SIV mode, described in [RFC 5297](https://www.rfc-editor.org/rfc/rfc5297)
- We also have AESKW and AESKWP from
[RFC 3394](https://www.rfc-editor.org/rfc/rfc3394) & [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
- Format-preserving encryption algorithm (FPE-FF1) specified in
[NIST SP 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf).
- Check out [AES block modes](#aes-block-modes),
[FIPS 197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf) and
[original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf).
- Polynomial-evaluation MACs are available: Poly1305, AES-GCM's GHash and AES-SIV's Polyval.
- Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
[website](https://cr.yp.to/mac.html))
is a fast and parallel secret-key message-authentication code suitable for
a wide variety of applications. It was standardized in
[RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.
- Ghash is used in AES-GCM: see NIST SP 800-38G
- Polyval is used in AES-GCM-SIV: see [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452)
##### AES block modes
For non-deterministic (not ECB) schemes, initialization vector (IV) is mixed to block/key;
and each new round either depends on previous block's key, or on some counter.
- **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield identical ciphertexts. Not secure due to pattern leakage. due to pattern leakage.
See [AES Penguin](https://words.filippo.io/the-ecb-penguin/)
- **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the previous block of ciphertext
before encryption. Hard to use: requires proper padding and an IV. Unauthenticated: needs MAC.
- **CTR** (Counter Mode): Turns a block cipher into a stream cipher using a counter and IV (nonce).
Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
- **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. Not perfect:
a) conservative key wear-out is `2**32` (4B) msgs.
b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
c) MAC can be forged: see Poly1305 documentation.
- **SIV** (Synthetic IV): GCM with nonce-misuse resistance; repeating nonces reveal only the fact plaintexts
are identical. Also suffers from GCM issues: key wear-out limits & MAC forging.
- **XTS**: Designed for disk encryption.
Similar to ECB (deterministic), but has `[i][j]` tweak arguments corresponding to
sector i and 16-byte block (part of sector) j. Lacks MAC.
## Security
The library has been audited:
- at version 2.2.0, in Apr 2026, by ourselves (self-audited)
- Scope: everything
- [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/2.2.0..main)
- at version 1.0.0, in Sep 2024, independently, by [cure53](https://cure53.de)
- PDFs: [website](https://cure53.de/audit-report_noble-crypto-libs.pdf), [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf)
- [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/1.0.0..main)
- Scope: everything
- The audit has been funded by [OpenSats](https://opensats.org)
It is tested against property-based, cross-library and Wycheproof vectors,
and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing).
If you see anything unusual: investigate and report.
### Constant-timeness
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance
in a scripting language. Which means _any other JS library can't have
constant-timeness_. Even statically typed Rust, a language without GC,
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.
Use low-level libraries & languages.
The library uses T-tables for AES, which
[leak access timings](https://cr.yp.to/antiforgery/cachetiming-20050414.pdf).
This is also done in [OpenSSL](https://github.com/openssl/openssl/blob/2f33265039cdbd0e4589c80970e02e208f3f94d2/crypto/aes/aes_core.c#L706) and
[Go stdlib](https://cs.opensource.google/go/go/+/refs/tags/go1.22.6:src/crypto/aes/const.go;l=90) for performance reasons.
The analysis was mentioned in [hal-04652991](https://hal.science/hal-04652991/document).
### Supply chain security
- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures
- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity.
- **Rare releasing** is practiced to minimize the need for re-audits by end-users.
- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk.
- We use as few dependencies as possible.
- Version ranges are locked, and changes are checked with npm-diff.
- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps.
For this package, there are 0 dependencies; and a few dev dependencies:
- jsbt is used for benchmarking / testing / build tooling and developed by the same author
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation
### Randomness
We rely on the built-in
[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues),
which is considered a cryptographically secure PRNG.
Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy.
### Quantum computers
Cryptographically relevant quantum computer, if built, will allow to
utilize Grover's algorithm to break ciphers in 2^n/2 operations, instead of 2^n.
This means AES128 should be replaced with AES256. Salsa and ChaCha are already safe.
Australian ASD prohibits AES128 [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
## Speed
```sh
npm run bench
```
Benchmarks measured on Apple M4.
If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble).
```
64B
xsalsa20poly1305 x 735,835 ops/sec @ 1μs/op
chacha20poly1305 x 581,395 ops/sec @ 1μs/op
xchacha20poly1305 x 468,384 ops/sec @ 2μs/op
aes-256-gcm x 201,126 ops/sec @ 4μs/op
aes-256-gcm-siv x 162,284 ops/sec @ 6μs/op
# Unauthenticated encryption
salsa20 x 1,655,629 ops/sec @ 604ns/op
xsalsa20 x 1,400,560 ops/sec @ 714ns/op
chacha20 x 1,996,007 ops/sec @ 501ns/op
xchacha20 x 1,404,494 ops/sec @ 712ns/op
chacha8 x 2,145,922 ops/sec @ 466ns/op
chacha12 x 2,036,659 ops/sec @ 491ns/op
aes-ecb-256 x 1,019,367 ops/sec @ 981ns/op
aes-cbc-256 x 931,966 ops/sec @ 1μs/op
aes-ctr-256 x 954,198 ops/sec @ 1μs/op
1MB
xsalsa20poly1305 x 334 ops/sec @ 2ms/op
chacha20poly1305 x 333 ops/sec @ 2ms/op
xchacha20poly1305 x 334 ops/sec @ 2ms/op
aes-256-gcm x 94 ops/sec @ 10ms/op
aes-256-gcm-siv x 90 ops/sec @ 11ms/op
# Unauthenticated encryption
salsa20 x 831 ops/sec @ 1ms/op
xsalsa20 x 830 ops/sec @ 1ms/op
chacha20 x 804 ops/sec @ 1ms/op
xchacha20 x 797 ops/sec @ 1ms/op
chacha8 x 1,495 ops/sec @ 668μs/op
chacha12 x 1,148 ops/sec @ 871μs/op
aes-ecb-256 x 289 ops/sec @ 3ms/op
aes-cbc-256 x 114 ops/sec @ 8ms/op
aes-ctr-256 x 127 ops/sec @ 7ms/op
# Wrapper over built-in webcrypto
webcrypto ctr-256 x 6,508 ops/sec @ 153μs/op
webcrypto cbc-256 x 1,820 ops/sec @ 549μs/op
webcrypto gcm-256 x 5,106 ops/sec @ 195μs/op
```
Compare to other implementations:
```
xsalsa20poly1305 (encrypt, 1MB)
├─tweetnacl x 196 mb/sec
├─awasm-noble_threads x 2,318 mb/sec
├─awasm-noble_no_threads x 1,196 mb/sec
└─noble x 305 mb/sec
aes-ctr-256 (encrypt, 1MB)
├─stablelib x 123 mb/sec
├─aesjs x 42 mb/sec
├─awasm-noble_thread x 2,105 mb/sec
├─awasm-noble_no_threads x 272 mb/sec
├─noble_webcrypto x 5,965 mb/sec
└─noble x 124 mb/sec
```
## Upgrading
Supported node.js versions:
- v2: v20.19+ (ESM-only)
- v1: v14.21+ (ESM & CJS)
Changelog of v2, when upgrading from ciphers v1:
- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+
- `.js` extension must be used for all modules
- Old: `@noble/ciphers/aes`
- New: `@noble/ciphers/aes.js`
- This simplifies working in browsers natively without transpilers
- webcrypto: move `randomBytes` and `managedNonce` to `utils.js`
- ghash, poly1305, polyval: only allow Uint8Array as hash inputs, prohibit `string`
- utils: new abytes; remove ahash, toBytes
- Remove modules `_assert` (use `utils`), `_micro` and `crypto` (use `webcrypto`)
- Bump TS compilation target from es2020 to es2022
- Massively improve error messages, make them more descriptive
## Contributing & testing
- `npm install && npm run build && npm test` will build the code and run tests.
- `npm run lint` / `npm run format` will run linter / fix linter issues.
- `npm run bench` will run benchmarks
- `npm run build:release` will build single file
See [paulmillr.com/noble](https://paulmillr.com/noble/)
for useful resources, articles, documentation and demos
related to the library.
## License
The MIT License (MIT)
Copyright (c) 2023 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
See LICENSE file.
+145
View File
@@ -0,0 +1,145 @@
/**
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
RFC8439 requires multi-step cipher stream, where
authKey starts with counter: 0, actual msg with counter: 1.
For this, we need a way to re-use nonce / counter:
const counter = new Uint8Array(4);
chacha(..., counter, ...); // counter is now 1
chacha(..., counter, ...); // counter is now 2
This is complicated:
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
- Original papers don't allow mutating counters
- Counter overflow is undefined [^1]
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
- Caveat: Cannot be re-used through all cases:
- * chacha has (counter | nonce)
- * xchacha has (nonce16 | counter | nonce16)
- Idea B: separate nonce / counter and provide separate API for counter re-use
- Caveat: there are different counter sizes depending on an algorithm.
- salsa & chacha also differ in structures of key & sigma:
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | cnt(1) | nonce(3)
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
Current noble policy is strict non-wrap for the shared 32-bit counter path:
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
wrap back to zero.
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
* @module
*/
import { type PRG, type TArg, type TRet, type XorStream } from './utils.ts';
/**
* Rotates a 32-bit word left.
* @param a - Input word.
* @param b - Rotation count in bits.
* @returns Rotated 32-bit word.
* @example
* Moves the top byte of `0x12345678` into the low byte position.
* ```ts
* rotl(0x12345678, 8);
* ```
*/
export declare function rotl(a: number, b: number): number;
/**
* ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.
* @param sigma - Sigma constants for the selected cipher layout.
* @param key - Expanded key words.
* @param nonce - Nonce and counter words prepared for the round function.
* @param output - Output block written in place.
* @param counter - Block counter value.
* @param rounds - Optional round count override.
*/
export type CipherCoreFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, nonce: TArg<Uint32Array>, output: TArg<Uint32Array>, counter: number, rounds?: number) => void;
/**
* Nonce-extension function used by XChaCha and XSalsa.
* @param sigma - Sigma constants for the selected cipher layout.
* @param key - Expanded key words.
* @param input - Input nonce words used for subkey derivation.
* @param output - Output buffer written with the derived nonce words.
*/
export type ExtendNonceFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, input: TArg<Uint32Array>, output: TArg<Uint32Array>) => void;
/** ARX cipher options.
* * `allowShortKeys` for 16-byte keys
* * `counterLength` in bytes
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
* */
export type CipherOpts = {
/** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */
allowShortKeys?: boolean;
/** Optional nonce-expansion hook used by extended-nonce variants. */
extendNonceFn?: ExtendNonceFn;
/** Counter length in bytes inside the nonce/counter layout. */
counterLength?: number;
/** Whether the layout is `nonce|counter` instead of `counter|nonce`. */
counterRight?: boolean;
/** Number of core rounds to execute. */
rounds?: number;
};
/**
* Creates an ARX stream cipher from a 32-bit core permutation.
* Used internally to build the exported Salsa and ChaCha stream ciphers.
* @param core - Core function that fills one keystream block.
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
* @returns Stream cipher function over byte arrays.
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
*/
export declare function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream>;
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
export declare class _XorStreamPRG implements PRG {
readonly blockLen: number;
readonly keyLen: number;
readonly nonceLen: number;
private state;
private buf;
private key;
private nonce;
private pos;
private ctr;
private cipher;
constructor(cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number, seed: TArg<Uint8Array>);
private reseed;
addEntropy(seed: TArg<Uint8Array>): void;
randomBytes(len: number): TRet<Uint8Array>;
clone(): _XorStreamPRG;
clean(): void;
}
/**
* PRG constructor backed by an ARX stream cipher.
* @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32
* random bytes are mixed in by default: larger states keep a zero tail, while smaller states
* wrap those bytes through `reseed()`'s XOR schedule.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
*/
export type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;
/**
* Creates a PRG constructor from a stream cipher.
* @param cipher - Stream cipher used to fill output blocks.
* @param blockLen - Keystream block length in bytes.
* @param keyLen - Internal key length in bytes.
* @param nonceLen - Internal nonce length in bytes.
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
* @example
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
* ```ts
* import { xchacha20 } from '@noble/ciphers/chacha.js';
* import { createPRG } from '@noble/ciphers/_arx.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const init = createPRG(xchacha20, 64, 32, 24);
* const prg = init(seed);
* prg.randomBytes(8);
* ```
*/
export declare const createPRG: (cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number) => TRet<XorPRG>;
//# sourceMappingURL=_arx.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_arx.d.ts","sourceRoot":"","sources":["src/_arx.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,EACL,KAAK,GAAG,EACR,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EAaf,MAAM,YAAY,CAAC;AAcpB;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,EACzB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,KACtB,IAAI,CAAC;AAEV;;;;KAIK;AACL,MAAM,MAAM,UAAU,GAAG;IACvB,8EAA8E;IAC9E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,qEAAqE;IACrE,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,+DAA+D;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,wEAAwE;IACxE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AA8FF;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAoG9F;AAED,uEAAuE;AACvE,qBAAa,aAAc,YAAW,GAAG;IACvC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,GAAG,CAAmB;IAC9B,OAAO,CAAC,GAAG,CAAmB;IAC9B,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,MAAM,CAAkB;gBAE9B,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EACvB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC;IAgBxB,OAAO,CAAC,MAAM;IASd,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IASxC,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;IA+C1C,KAAK,IAAI,aAAa;IAYtB,KAAK,IAAI,IAAI;CAMd;AAED;;;;;;GAMG;AACH,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,aAAa,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,SAAS,GACpB,QAAQ,IAAI,CAAC,SAAS,CAAC,EACvB,UAAU,MAAM,EAChB,QAAQ,MAAM,EACd,UAAU,MAAM,KACf,IAAI,CAAC,MAAM,CASb,CAAC"}
+369
View File
@@ -0,0 +1,369 @@
/**
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
RFC8439 requires multi-step cipher stream, where
authKey starts with counter: 0, actual msg with counter: 1.
For this, we need a way to re-use nonce / counter:
const counter = new Uint8Array(4);
chacha(..., counter, ...); // counter is now 1
chacha(..., counter, ...); // counter is now 2
This is complicated:
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
- Original papers don't allow mutating counters
- Counter overflow is undefined [^1]
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
- Caveat: Cannot be re-used through all cases:
- * chacha has (counter | nonce)
- * xchacha has (nonce16 | counter | nonce16)
- Idea B: separate nonce / counter and provide separate API for counter re-use
- Caveat: there are different counter sizes depending on an algorithm.
- salsa & chacha also differ in structures of key & sigma:
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | cnt(1) | nonce(3)
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
Current noble policy is strict non-wrap for the shared 32-bit counter path:
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
wrap back to zero.
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
* @module
*/
import { abool, abytes, anumber, checkOpts, clean, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from "./utils.js";
// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
// Non-ASCII input would not match UTF-8 `TextEncoder` output.
const encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
// kept for legacy allowShortKeys Salsa/ChaCha variants.
const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
/**
* Rotates a 32-bit word left.
* @param a - Input word.
* @param b - Rotation count in bits.
* @returns Rotated 32-bit word.
* @example
* Moves the top byte of `0x12345678` into the low byte position.
* ```ts
* rotl(0x12345678, 8);
* ```
*/
export function rotl(a, b) {
return (a << b) | (a >>> (32 - b));
}
// Salsa and Chacha block length is always 512-bit
const BLOCK_LEN = 64;
// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
const BLOCK_LEN32 = 16;
// Counter policy for the shared public `counter` argument:
// - RFC/IETF ChaCha20 uses a 32-bit counter.
// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
// counter state and carry into the next word.
// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
// boundary instead of carrying.
// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
// Noble intentionally throws instead of silently picking one wrap model for users. In the default
// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
// whatever wider carry / wrap policy they need on top.
const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
const len = data.length;
const block = new Uint8Array(BLOCK_LEN);
const b32 = u32(block);
// Make sure that buffers aligned to 4 bytes
const isAligned = isLE && isAligned32(data) && isAligned32(output);
const d32 = isAligned ? u32(data) : U32_EMPTY;
const o32 = isAligned ? u32(output) : U32_EMPTY;
// RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
// truncating the final partial block instead of materializing the whole keystream.
if (!isLE) {
for (let pos = 0; pos < len; counter++) {
core(sigma, key, nonce, b32, counter, rounds);
// RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
swap32IfBE(b32);
if (counter >= MAX_COUNTER)
throw new Error('arx: counter overflow');
const take = Math.min(BLOCK_LEN, len - pos);
for (let j = 0, posj; j < take; j++) {
posj = pos + j;
output[posj] = data[posj] ^ block[j];
}
pos += take;
}
return;
}
for (let pos = 0; pos < len; counter++) {
core(sigma, key, nonce, b32, counter, rounds);
// See MAX_COUNTER policy note above: never silently wrap the shared public counter.
if (counter >= MAX_COUNTER)
throw new Error('arx: counter overflow');
const take = Math.min(BLOCK_LEN, len - pos);
// aligned to 4 bytes
if (isAligned && take === BLOCK_LEN) {
const pos32 = pos / 4;
if (pos % 4 !== 0)
throw new Error('arx: invalid block position');
for (let j = 0, posj; j < BLOCK_LEN32; j++) {
posj = pos32 + j;
o32[posj] = d32[posj] ^ b32[j];
}
pos += BLOCK_LEN;
continue;
}
for (let j = 0, posj; j < take; j++) {
posj = pos + j;
output[posj] = data[posj] ^ block[j];
}
pos += take;
}
}
/**
* Creates an ARX stream cipher from a 32-bit core permutation.
* Used internally to build the exported Salsa and ChaCha stream ciphers.
* @param core - Core function that fills one keystream block.
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
* @returns Stream cipher function over byte arrays.
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
*/
export function createCipher(core, opts) {
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
if (typeof core !== 'function')
throw new Error('core must be a function');
anumber(counterLength);
anumber(rounds);
abool(counterRight);
abool(allowShortKeys);
return (key, nonce, data, output, counter = 0) => {
abytes(key, undefined, 'key');
abytes(nonce, undefined, 'nonce');
abytes(data, undefined, 'data');
const len = data.length;
// Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
// must match the logical result length exactly instead of returning an oversized workspace.
output = getOutput(len, output, false);
anumber(counter);
// See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
if (counter < 0 || counter >= MAX_COUNTER)
throw new Error('arx: counter overflow');
const toClean = [];
// Key & sigma
// key=16 -> sigma16, k=key|key
// key=32 -> sigma32, k=key
let l = key.length;
let k;
let sigma;
if (l === 32) {
// Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
// final clean(...) all mutate or wipe the temporary buffer in place.
toClean.push((k = copyBytes(key)));
sigma = sigma32_32;
}
else if (l === 16 && allowShortKeys) {
k = new Uint8Array(32);
k.set(key);
k.set(key, 16);
sigma = sigma16_32;
toClean.push(k);
}
else {
abytes(key, 32, 'arx key');
throw new Error('invalid key size');
// throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
}
// Nonce
// salsa20: 8 (8-byte counter)
// chacha20orig: 8 (8-byte counter)
// chacha20: 12 (4-byte counter)
// xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
// xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
// Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
// swap32IfBE(...) never mutates caller nonce bytes in place.
if (!isLE || !isAligned32(nonce))
toClean.push((nonce = copyBytes(nonce)));
let k32 = u32(k);
// hsalsa & hchacha: handle extended nonce
if (extendNonceFn) {
if (nonce.length !== 24)
throw new Error(`arx: extended nonce must be 24 bytes`);
const n16 = nonce.subarray(0, 16);
if (isLE)
extendNonceFn(sigma, k32, u32(n16), k32);
else {
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
clean(sigmaRaw);
swap32IfBE(k32);
}
nonce = nonce.subarray(16);
}
else if (!isLE)
swap32IfBE(k32);
// Handle nonce counter
const nonceNcLen = 16 - counterLength;
if (nonceNcLen !== nonce.length)
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
// Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
// counter bytes, while Salsa/XSalsa append them after the nonce words.
if (nonceNcLen !== 12) {
const nc = new Uint8Array(12);
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
nonce = nc;
toClean.push(nonce);
}
const n32 = swap32IfBE(u32(nonce));
// Ensure temporary key/nonce copies are wiped even if the remaining
// runtime guard in runCipher(...) throws on counter overflow.
try {
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
return output;
}
finally {
clean(...toClean);
}
};
}
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
export class _XorStreamPRG {
blockLen;
keyLen;
nonceLen;
state;
buf;
key;
nonce;
pos;
ctr;
cipher;
constructor(cipher, blockLen, keyLen, nonceLen, seed) {
this.cipher = cipher;
this.blockLen = blockLen;
this.keyLen = keyLen;
this.nonceLen = nonceLen;
this.state = new Uint8Array(this.keyLen + this.nonceLen);
this.reseed(seed);
this.ctr = 0;
this.pos = this.blockLen;
this.buf = new Uint8Array(this.blockLen);
// Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
// inputs in place through these subarray views.
this.key = this.state.subarray(0, this.keyLen);
this.nonce = this.state.subarray(this.keyLen);
}
reseed(seed) {
abytes(seed);
if (!seed || seed.length === 0)
throw new Error('entropy required');
// Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
// keystream so buffered leftovers from the previous state are never reused.
for (let i = 0; i < seed.length; i++)
this.state[i % this.state.length] ^= seed[i];
this.ctr = 0;
this.pos = this.blockLen;
}
addEntropy(seed) {
// Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
abytes(seed);
if (seed.length === 0)
throw new Error('entropy required');
// Re-key from the current stream first, then mix external entropy into the fresh key||nonce
// state through reseed() so stale buffered bytes are discarded.
this.state.set(this.randomBytes(this.state.length));
this.reseed(seed);
}
randomBytes(len) {
anumber(len);
if (len === 0)
return new Uint8Array(0);
const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
// Preflight overflow so failed reads don't partially consume keystream
// and leave the PRG repeating blocks.
if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)
throw new Error('arx: counter overflow');
const out = new Uint8Array(len);
let outPos = 0;
// `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
// ciphers then emit raw keystream bytes directly into those buffers.
// Serve buffered leftovers first so split reads stay identical to one larger read.
if (this.pos < this.blockLen) {
const take = Math.min(len, this.blockLen - this.pos);
out.set(this.buf.subarray(this.pos, this.pos + take), 0);
this.pos += take;
outPos += take;
if (outPos === len)
return out; // fast path
}
// Full blocks directly to out
const full = Math.floor((len - outPos) / this.blockLen);
if (full > 0) {
const blockBytes = full * this.blockLen;
const b = out.subarray(outPos, outPos + blockBytes);
this.cipher(this.key, this.nonce, b, b, this.ctr);
this.ctr += full;
outPos += blockBytes;
}
// Save leftovers
const left = len - outPos;
if (left > 0) {
this.buf.fill(0);
// NOTE: cipher will handle overflow
this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);
out.set(this.buf.subarray(0, left), outPos);
this.pos = left;
}
return out;
}
// Clone seeds the new instance from this stream, so the source PRG advances too.
clone() {
return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));
}
// Zeroes the current state and leftover buffer, but does not make the instance unusable:
// Later reads first drain zeros from the cleared buffer and then continue
// from zero key||nonce state.
clean() {
this.pos = 0;
this.ctr = 0;
this.buf.fill(0);
this.state.fill(0);
}
}
/**
* Creates a PRG constructor from a stream cipher.
* @param cipher - Stream cipher used to fill output blocks.
* @param blockLen - Keystream block length in bytes.
* @param keyLen - Internal key length in bytes.
* @param nonceLen - Internal nonce length in bytes.
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
* @example
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
* ```ts
* import { xchacha20 } from '@noble/ciphers/chacha.js';
* import { createPRG } from '@noble/ciphers/_arx.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const init = createPRG(xchacha20, 64, 32, 24);
* const prg = init(seed);
* prg.randomBytes(8);
* ```
*/
export const createPRG = (cipher, blockLen, keyLen, nonceLen) => {
return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));
};
//# sourceMappingURL=_arx.js.map
+1
View File
File diff suppressed because one or more lines are too long
+73
View File
@@ -0,0 +1,73 @@
/**
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
*
* Polynomial MACs are not perfect for every situation:
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
* however, this would violate ciphertext indistinguishability:
* an attacker would know which key was used - so `HKDF(key, i)`
* could be used instead.
*
* Check out the {@link https://cr.yp.to/mac.html | original website}.
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
* @module
*/
import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts';
/**
* Incremental Poly1305 MAC state.
* Prefer `poly1305()` for one-shot use.
* @param key - 32-byte Poly1305 one-time key.
* @example
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
*
* ```ts
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const mac = new Poly1305(key);
* mac.update(new Uint8Array([1, 2, 3]));
* mac.digest();
* ```
*/
export declare class Poly1305 implements IHash2 {
readonly blockLen = 16;
readonly outputLen = 16;
private buffer;
private r;
private h;
private pad;
private pos;
protected finished: boolean;
protected destroyed: boolean;
constructor(key: TArg<Uint8Array>);
private process;
private finalize;
update(data: TArg<Uint8Array>): this;
destroy(): void;
digestInto(out: TArg<Uint8Array>): void;
digest(): TRet<Uint8Array>;
}
/** One-shot keyed hash helper with `.create()`. */
export type CHash = CMac<Poly1305>;
/**
* Poly1305 MAC from RFC 8439.
* @param msg - Message bytes to authenticate.
* @param key - 32-byte Poly1305 one-time key.
* @returns 16-byte authentication tag.
* @example
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
*
* ```ts
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* poly1305(new Uint8Array(), key);
* ```
*/
export declare const poly1305: TRet<CHash>;
//# sourceMappingURL=_poly1305.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_poly1305.d.ts","sourceRoot":"","sources":["src/_poly1305.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAGe,KAAK,IAAI,EAAE,KAAK,MAAM,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EACjE,MAAM,YAAY,CAAC;AA2DpB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,QAAS,YAAW,MAAM;IACrC,QAAQ,CAAC,QAAQ,MAAM;IACvB,QAAQ,CAAC,SAAS,MAAM;IACxB,OAAO,CAAC,MAAM,CAAsB;IACpC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,GAAG,CAAsB;IACjC,OAAO,CAAC,GAAG,CAAK;IAChB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;gBAGhB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC;IA4BjC,OAAO,CAAC,OAAO;IA+Hf,OAAO,CAAC,QAAQ;IAmDhB,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAwBpC,OAAO,IAAI,IAAI;IAKf,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAqBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAQ3B;AAED,mDAAmD;AACnD,MAAM,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;AAEnC;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAGhC,CAAC"}
+364
View File
@@ -0,0 +1,364 @@
/**
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
*
* Polynomial MACs are not perfect for every situation:
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
* however, this would violate ciphertext indistinguishability:
* an attacker would know which key was used - so `HKDF(key, i)`
* could be used instead.
*
* Check out the {@link https://cr.yp.to/mac.html | original website}.
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
* @module
*/
// prettier-ignore
import { abytes, aexists, aoutput, bytesToHex, clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE, wrapMacConstructor } from "./utils.js";
// Little-endian 2-byte load used by the Poly1305 limb decomposition.
function u8to16(a, i) {
return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
}
function bytesToNumberLE(bytes) {
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */
function poly1305_small(msg, key) {
abytes(msg);
abytes(key, 32, 'key');
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5
const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
const s = bytesToNumberLE(key.subarray(16));
// Process by 16 byte chunks
let acc = BigInt(0);
for (let i = 0; i < msg.length; i += 16) {
const m = msg.subarray(i, i + 16);
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r.
const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));
acc = ((acc + n) * r) % POW_2_130_5;
}
const res = (acc + s) & POW_2_128_1;
// RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order.
return numberToBytesBE(res, 16).reverse(); // LE
}
// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.
// @ts-expect-error
function poly1305_computeTag_small(authKey,
// AEAD trailer must already be the 16-byte length block:
// 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.
lengths, ciphertext, AAD) {
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is
// AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.
const res = [];
const updatePadded2 = (msg) => {
res.push(msg);
const leftover = msg.length % 16;
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned
// inputs, else 16-(len%16) zero bytes.
if (leftover)
res.push(new Uint8Array(16).slice(leftover));
};
if (AAD)
updatePadded2(AAD);
updatePadded2(ciphertext);
res.push(lengths);
return poly1305_small(concatBytes(...res), authKey);
}
/**
* Incremental Poly1305 MAC state.
* Prefer `poly1305()` for one-shot use.
* @param key - 32-byte Poly1305 one-time key.
* @example
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
*
* ```ts
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const mac = new Poly1305(key);
* mac.update(new Uint8Array([1, 2, 3]));
* mac.digest();
* ```
*/
export class Poly1305 {
blockLen = 16;
outputLen = 16;
buffer = new Uint8Array(16);
r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
h = new Uint16Array(10);
pad = new Uint16Array(8);
pos = 0;
finished = false;
destroyed = false;
// Can be speed-up using BigUint64Array, at the cost of complexity
constructor(key) {
key = copyBytes(abytes(key, 32, 'key'));
const t0 = u8to16(key, 0);
const t1 = u8to16(key, 2);
const t2 = u8to16(key, 4);
const t3 = u8to16(key, 6);
const t4 = u8to16(key, 8);
const t5 = u8to16(key, 10);
const t6 = u8to16(key, 12);
const t7 = u8to16(key, 14);
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
// These masks unpack that clamped value into 13-bit limbs, while pad
// keeps the raw s half for finalize().
// {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
this.r[0] = t0 & 0x1fff;
this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
this.r[5] = (t4 >>> 1) & 0x1ffe;
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
this.r[9] = (t7 >>> 5) & 0x007f;
for (let i = 0; i < 8; i++)
this.pad[i] = u8to16(key, 16 + 2 * i);
}
process(data, offset, isLast = false) {
// RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
// bit to every full 16-byte block. The final partial block gets its
// explicit `1` byte during digestInto(), so `hibit` stays zero there.
const hibit = isLast ? 0 : 1 << 11;
const { h, r } = this;
const r0 = r[0];
const r1 = r[1];
const r2 = r[2];
const r3 = r[3];
const r4 = r[4];
const r5 = r[5];
const r6 = r[6];
const r7 = r[7];
const r8 = r[8];
const r9 = r[9];
const t0 = u8to16(data, offset + 0);
const t1 = u8to16(data, offset + 2);
const t2 = u8to16(data, offset + 4);
const t3 = u8to16(data, offset + 6);
const t4 = u8to16(data, offset + 8);
const t5 = u8to16(data, offset + 10);
const t6 = u8to16(data, offset + 12);
const t7 = u8to16(data, offset + 14);
let h0 = h[0] + (t0 & 0x1fff);
let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
let h9 = h[9] + ((t7 >>> 5) | hibit);
let c = 0;
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
c = d0 >>> 13;
d0 &= 0x1fff;
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
c += d0 >>> 13;
d0 &= 0x1fff;
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
c = d1 >>> 13;
d1 &= 0x1fff;
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
c += d1 >>> 13;
d1 &= 0x1fff;
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
c = d2 >>> 13;
d2 &= 0x1fff;
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
c += d2 >>> 13;
d2 &= 0x1fff;
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
c = d3 >>> 13;
d3 &= 0x1fff;
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
c += d3 >>> 13;
d3 &= 0x1fff;
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
c = d4 >>> 13;
d4 &= 0x1fff;
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
c += d4 >>> 13;
d4 &= 0x1fff;
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
c = d5 >>> 13;
d5 &= 0x1fff;
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
c += d5 >>> 13;
d5 &= 0x1fff;
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
c = d6 >>> 13;
d6 &= 0x1fff;
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
c += d6 >>> 13;
d6 &= 0x1fff;
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
c = d7 >>> 13;
d7 &= 0x1fff;
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
c += d7 >>> 13;
d7 &= 0x1fff;
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
c = d8 >>> 13;
d8 &= 0x1fff;
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
c += d8 >>> 13;
d8 &= 0x1fff;
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
c = d9 >>> 13;
d9 &= 0x1fff;
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
c += d9 >>> 13;
d9 &= 0x1fff;
c = ((c << 2) + c) | 0;
c = (c + d0) | 0;
d0 = c & 0x1fff;
c = c >>> 13;
d1 += c;
h[0] = d0;
h[1] = d1;
h[2] = d2;
h[3] = d3;
h[4] = d4;
h[5] = d5;
h[6] = d6;
h[7] = d7;
h[8] = d8;
h[9] = d9;
}
finalize() {
const { h, pad } = this;
const g = new Uint16Array(10);
let c = h[1] >>> 13;
h[1] &= 0x1fff;
for (let i = 2; i < 10; i++) {
h[i] += c;
c = h[i] >>> 13;
h[i] &= 0x1fff;
}
h[0] += c * 5;
c = h[0] >>> 13;
h[0] &= 0x1fff;
h[1] += c;
c = h[1] >>> 13;
h[1] &= 0x1fff;
h[2] += c;
// RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
// to 16-bit words and adding the raw s half.
g[0] = h[0] + 5;
c = g[0] >>> 13;
g[0] &= 0x1fff;
for (let i = 1; i < 10; i++) {
g[i] = h[i] + c;
c = g[i] >>> 13;
g[i] &= 0x1fff;
}
g[9] -= 1 << 13;
let mask = (c ^ 1) - 1;
for (let i = 0; i < 10; i++)
g[i] &= mask;
mask = ~mask;
for (let i = 0; i < 10; i++)
h[i] = (h[i] & mask) | g[i];
h[0] = (h[0] | (h[1] << 13)) & 0xffff;
h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
let f = h[0] + pad[0];
h[0] = f & 0xffff;
for (let i = 1; i < 8; i++) {
f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
h[i] = f & 0xffff;
}
clean(g);
}
update(data) {
aexists(this);
abytes(data);
data = copyBytes(data);
const { buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path: we have at least one block in input
if (take === blockLen) {
for (; blockLen <= len - pos; pos += blockLen)
this.process(data, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(buffer, 0, false);
this.pos = 0;
}
}
return this;
}
destroy() {
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
this.destroyed = true;
clean(this.h, this.r, this.buffer, this.pad);
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
const { buffer, h } = this;
let { pos } = this;
if (pos) {
// RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
// single `0x01` byte and zero-fills the remaining bytes before the
// last multiplication step.
buffer[pos++] = 1;
for (; pos < 16; pos++)
buffer[pos] = 0;
this.process(buffer, 0, true);
}
this.finalize();
let opos = 0;
for (let i = 0; i < 8; i++) {
out[opos++] = h[i] >>> 0;
out[opos++] = h[i] >>> 8;
}
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
// Copy out before destroy() zeroes the internal buffer.
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
}
/**
* Poly1305 MAC from RFC 8439.
* @param msg - Message bytes to authenticate.
* @param key - 32-byte Poly1305 one-time key.
* @returns 16-byte authentication tag.
* @example
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
*
* ```ts
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* poly1305(new Uint8Array(), key);
* ```
*/
export const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
//# sourceMappingURL=_poly1305.js.map
+1
View File
File diff suppressed because one or more lines are too long
+121
View File
@@ -0,0 +1,121 @@
/**
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
*
* Implemented in terms of GHash with conversion function for keys
* GCM GHASH from
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
* SIV from
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts';
/**
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
* @param k mutated in place
*/
export declare function _toGHASHKey(k: TArg<Uint8Array>): TRet<Uint8Array>;
type Value = {
s0: number;
s1: number;
s2: number;
s3: number;
};
/**
* Incremental GHASH state for AES-GCM.
* @param key - 16-byte GHASH key.
* @param expectedLength - Expected message length for table sizing.
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
* use where AAD, payload, and length block are separate padded segments.
* @example
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
*
* ```ts
* import { GHASH } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const mac = new GHASH(key);
* mac.update(new Uint8Array(16));
* mac.digest();
* ```
*/
export declare class GHASH implements IHash2 {
readonly blockLen: number;
readonly outputLen: number;
protected s0: number;
protected s1: number;
protected s2: number;
protected s3: number;
protected finished: boolean;
protected destroyed: boolean;
protected t: Value[];
private W;
private windowSize;
constructor(key: TArg<Uint8Array>, expectedLength?: number);
protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void;
update(data: TArg<Uint8Array>): this;
destroy(): void;
digestInto(out: TArg<Uint8Array>): void;
digest(): TRet<Uint8Array>;
}
/**
* Incremental POLYVAL state for AES-SIV.
* @param key - 16-byte POLYVAL key.
* @param expectedLength - Expected message length for table sizing.
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
* independently to a 16-byte boundary before absorption.
* @example
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
*
* ```ts
* import { Polyval } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const mac = new Polyval(key);
* mac.update(new Uint8Array(16));
* mac.digest();
* ```
*/
export declare class Polyval extends GHASH {
constructor(key: TArg<Uint8Array>, expectedLength?: number);
update(data: TArg<Uint8Array>): this;
digestInto(out: TArg<Uint8Array>): void;
}
/**
* GHash MAC for AES-GCM.
* @param msg - Message bytes to authenticate.
* @param key - 16-byte GHASH key.
* @returns 16-byte authentication tag.
* @example
* Authenticates a short message with GHASH and a fresh hash key.
*
* ```ts
* import { ghash } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* ghash(new Uint8Array(), key);
* ```
*/
export declare const ghash: TRet<CMac<GHASH, [expectedLength?: number]>>;
/**
* POLYVAL MAC for AES-SIV.
* @param msg - Message bytes to authenticate.
* @param key - 16-byte POLYVAL key.
* @returns 16-byte authentication tag.
* @example
* Authenticates a short message with POLYVAL and a fresh hash key.
*
* ```ts
* import { polyval } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* polyval(new Uint8Array(), key);
* ```
*/
export declare const polyval: TRet<CMac<Polyval, [expectedLength?: number]>>;
export {};
//# sourceMappingURL=_polyval.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_polyval.d.ts","sourceRoot":"","sources":["src/_polyval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAWL,KAAK,IAAI,EACT,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAuCpB;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAcjE;AAED,KAAK,KAAK,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAUhE;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,KAAM,YAAW,MAAM;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAc;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAc;IACxC,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;IAC5B,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,CAAC,CAAS;IAClB,OAAO,CAAC,UAAU,CAAS;gBAEf,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC,EAAE,MAAM;IAuC1D,SAAS,CAAC,YAAY,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,IAAI;IA0B5E,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA6BpC,OAAO,IAAI,IAAI;IAWf,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAiBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAO3B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,OAAQ,SAAQ,KAAK;gBACpB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC,EAAE,MAAM;IAS1D,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA6BpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;CAkBxC;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAK5D,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAKhE,CAAC"}
+330
View File
@@ -0,0 +1,330 @@
/**
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
*
* Implemented in terms of GHash with conversion function for keys
* GCM GHASH from
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
* SIV from
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
import { abytes, aexists, aoutput, clean, copyBytes, createView, swap32IfBE, swap8IfBE, u32, wrapMacConstructor, } from "./utils.js";
const BLOCK_SIZE = 16;
// TODO: rewrite
// temporary padding buffer
// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
const ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
const POLY = 0xe1;
// v = 2*v % POLY
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
// Montgomery ladder can multiply any field element with this doubling step;
// addition stays simple xor.
const mul2 = (s0, s1, s2, s3) => {
const hiBit = s3 & 1;
return {
s3: (s2 << 31) | (s3 >>> 1),
s2: (s1 << 31) | (s2 >>> 1),
s1: (s0 << 31) | (s1 >>> 1),
// NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
// 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
};
};
// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
(((n >>> 8) & 0xff) << 16) |
(((n >>> 16) & 0xff) << 8) |
((n >>> 24) & 0xff) |
0;
// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
const swap8IfLE = (n) => swap8IfBE(swapLE(n));
/**
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
* @param k mutated in place
*/
export function _toGHASHKey(k) {
// The input is the original POLYVAL key H; reverse() materializes
// RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
k.reverse();
const hiBit = k[15] & 1;
// k >>= 1
let carry = 0;
for (let i = 0; i < k.length; i++) {
const t = k[i];
k[i] = (t >>> 1) | carry;
carry = (t & 1) << 7;
}
k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
return k;
}
// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
const estimateWindow = (bytes) => {
if (bytes > 64 * 1024)
return 8;
if (bytes > 1024)
return 4;
return 2;
};
/**
* Incremental GHASH state for AES-GCM.
* @param key - 16-byte GHASH key.
* @param expectedLength - Expected message length for table sizing.
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
* use where AAD, payload, and length block are separate padded segments.
* @example
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
*
* ```ts
* import { GHASH } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const mac = new GHASH(key);
* mac.update(new Uint8Array(16));
* mac.digest();
* ```
*/
export class GHASH {
blockLen = BLOCK_SIZE;
outputLen = BLOCK_SIZE;
s0 = 0;
s1 = 0;
s2 = 0;
s3 = 0;
finished = false;
destroyed = false;
t;
W;
windowSize;
// We select bits per window adaptively based on expectedLength
constructor(key, expectedLength) {
abytes(key, 16, 'key');
key = copyBytes(key);
const kView = createView(key);
let k0 = kView.getUint32(0, false);
let k1 = kView.getUint32(4, false);
let k2 = kView.getUint32(8, false);
let k3 = kView.getUint32(12, false);
// generate table of doubled keys (half of montgomery ladder)
const doubles = [];
for (let i = 0; i < 128; i++) {
doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
}
const W = estimateWindow(expectedLength || 1024);
if (![1, 2, 4, 8].includes(W))
throw new Error('ghash: invalid window size, expected 2, 4 or 8');
this.W = W;
const bits = 128; // always 128 bits;
const windows = bits / W;
const windowSize = (this.windowSize = 2 ** W);
const items = [];
// Create precompute table for window of W bits
for (let w = 0; w < windows; w++) {
// truth table: 00, 01, 10, 11
for (let byte = 0; byte < windowSize; byte++) {
// prettier-ignore
let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
for (let j = 0; j < W; j++) {
const bit = (byte >>> (W - j - 1)) & 1;
if (!bit)
continue;
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
}
items.push({ s0, s1, s2, s3 });
}
}
this.t = items;
}
_updateBlock(s0, s1, s2, s3) {
((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
const { W, t, windowSize } = this;
// prettier-ignore
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
const mask = (1 << W) - 1; // 2**W will kill performance.
let w = 0;
// NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
// so the lookup walk consumes each word byte-by-byte from
// least-significant to most-significant bits.
for (const num of [s0, s1, s2, s3]) {
for (let bytePos = 0; bytePos < 4; bytePos++) {
const byte = (num >>> (8 * bytePos)) & 0xff;
for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
const bit = (byte >>> (W * bitPos)) & mask;
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
w += 1;
}
}
}
this.s0 = o0;
this.s1 = o1;
this.s2 = o2;
this.s3 = o3;
}
update(data) {
aexists(this);
abytes(data);
data = copyBytes(data);
const b32 = u32(data);
const blocks = Math.floor(data.length / BLOCK_SIZE);
const left = data.length % BLOCK_SIZE;
for (let i = 0; i < blocks; i++) {
this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
// Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
// normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));
clean(ZEROS32); // clean tmp buffer
}
return this;
}
destroy() {
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
this.destroyed = true;
const { t } = this;
// Wipe the key-derived precompute table; scalar accumulator words remain,
// but the destroyed guard blocks further use.
// clean precompute table
for (const elm of t) {
((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
}
}
digestInto(out) {
aexists(this);
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
// 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
aoutput(out, this, true);
this.finished = true;
// NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
// `digestInto()` follows the relaxed `aoutput()` contract, so only
// out[0..15] may be touched.
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
swap32IfBE(o32);
}
digest() {
const res = new Uint8Array(BLOCK_SIZE);
this.digestInto(res);
// `res` is independent of internal state, so it stays valid after destroy() wipes the table.
this.destroy();
return res;
}
}
/**
* Incremental POLYVAL state for AES-SIV.
* @param key - 16-byte POLYVAL key.
* @param expectedLength - Expected message length for table sizing.
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
* independently to a 16-byte boundary before absorption.
* @example
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
*
* ```ts
* import { Polyval } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const mac = new Polyval(key);
* mac.update(new Uint8Array(16));
* mac.digest();
* ```
*/
export class Polyval extends GHASH {
constructor(key, expectedLength) {
abytes(key);
// RFC 8452 Appendix A converts the POLYVAL key with
// `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
// mutates in place.
const ghKey = _toGHASHKey(copyBytes(key));
super(ghKey, expectedLength);
clean(ghKey);
}
update(data) {
aexists(this);
abytes(data);
data = copyBytes(data);
const b32 = u32(data);
const left = data.length % BLOCK_SIZE;
const blocks = Math.floor(data.length / BLOCK_SIZE);
for (let i = 0; i < blocks; i++) {
// RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
// reverses the 32-bit word order in addition to the per-word byte swap.
this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));
clean(ZEROS32);
}
return this;
}
digestInto(out) {
aexists(this);
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
// 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
aoutput(out, this, true);
this.finished = true;
// RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
// `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
const view = out.subarray(0, this.outputLen);
const { s0, s1, s2, s3 } = this;
const o32 = u32(view);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
swap32IfBE(o32);
view.reverse();
}
}
/**
* GHash MAC for AES-GCM.
* @param msg - Message bytes to authenticate.
* @param key - 16-byte GHASH key.
* @returns 16-byte authentication tag.
* @example
* Authenticates a short message with GHASH and a fresh hash key.
*
* ```ts
* import { ghash } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* ghash(new Uint8Array(), key);
* ```
*/
export const ghash =
/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);
/**
* POLYVAL MAC for AES-SIV.
* @param msg - Message bytes to authenticate.
* @param key - 16-byte POLYVAL key.
* @returns 16-byte authentication tag.
* @example
* Authenticates a short message with POLYVAL and a fresh hash key.
*
* ```ts
* import { polyval } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* polyval(new Uint8Array(), key);
* ```
*/
export const polyval =
/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]);
//# sourceMappingURL=_polyval.js.map
+1
View File
File diff suppressed because one or more lines are too long
+462
View File
@@ -0,0 +1,462 @@
import { type Cipher, type CipherWithOutput, type CMac, type IHash2, type PRG, type TArg, type TRet, type Uint8ArrayBuffer } from './utils.ts';
/**
* Increments a counter block with wrap around.
* AES call sites here currently use the big-endian branch, but the helper supports both layouts.
* NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the
* least-significant/rightmost bits.
* `isLE=false` matches that standard counter-block layout, while `isLE=true`
* is a generic extension for non-AES callers.
* The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;
* larger values throw instead of silently overflowing before the next-byte propagation step.
*/
declare const incBytes: (data: TArg<Uint8Array>, isLE: boolean, carry?: number) => void;
/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */
declare function expandKeyLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
declare function expandKeyDecLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
declare function encrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
s0: number;
s1: number;
s2: number;
s3: number;
};
declare function decrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
s0: number;
s1: number;
s2: number;
s3: number;
};
declare function ctrCounter(xk: TArg<Uint32Array>, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
declare function ctr32(xk: TArg<Uint32Array>, isLE: boolean, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
/**
* **CTR** (Counter Mode): turns a block cipher into a stream cipher using a
* full 16-byte counter block.
* Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
* @param key - AES key bytes.
* @param nonce - 16-byte counter block, incremented as a full AES block.
* @returns Cipher instance with `encrypt()` and `decrypt()`.
* @example
* Encrypts a short payload with a fresh AES key and counter block.
*
* ```ts
* import { ctr } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(16);
* const cipher = ctr(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const ctr: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
}>;
/** Options for ECB and CBC. */
export type BlockOpts = {
/** Disable the library's PKCS#7 padding/unpadding layer and require exact-block inputs. */
disablePadding?: boolean;
};
/**
* **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield
* identical ciphertexts. Not secure due to pattern leakage.
* See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.
* @param key - AES key bytes.
* @param opts - Padding options. See {@link BlockOpts}.
* @returns Cipher instance with `encrypt()` and `decrypt()`.
* @example
* Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.
*
* ```ts
* import { ecb } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const cipher = ecb(key);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const ecb: TRet<((key: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
}>;
/**
* **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the
* previous block of ciphertext before encryption.
* Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.
* @param key - AES key bytes.
* @param iv - 16-byte unpredictable initialization vector.
* @param opts - Padding options. See {@link BlockOpts}.
* @returns Cipher instance with `encrypt()` and `decrypt()`.
* @example
* Encrypts a padded message with a fresh key and 16-byte IV.
*
* ```ts
* import { cbc } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const iv = randomBytes(16);
* const cipher = cbc(key, iv);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const cbc: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
}>;
/**
* CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the
* block cipher is the previous cipher output.
* Unauthenticated: needs MAC.
* @param key - AES key bytes.
* @param iv - 16-byte unpredictable initialization vector.
* @returns Cipher instance with `encrypt()` and `decrypt()`.
* @example
* Encrypts a short message with feedback mode and a fresh key/IV pair.
*
* ```ts
* import { cfb } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const iv = randomBytes(16);
* const cipher = cfb(key, iv);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const cfb: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
}>;
/**
* **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.
* Not perfect:
* a) conservative key wear-out is `2**32` (4B) msgs.
* b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
* c) MAC can be forged: see Poly1305 documentation.
* @param key - AES key bytes.
* @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance with a fixed 16-byte tag.
* @example
* Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.
*
* ```ts
* import { gcm } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(12);
* const cipher = gcm(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const gcm: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
}>;
/**
* **SIV** (Synthetic IV): GCM with nonce-misuse resistance.
* Repeating nonces reveal only the fact plaintexts are identical.
* Also suffers from GCM issues: key wear-out limits & MAC forging.
* See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
* RFC 8452 defines 16-byte and 32-byte AES keys for this mode.
* This implementation also accepts 24-byte AES-192 keys as a local
* extension; see the inline comment next to `validateKeyLength(key)` below
* for the exact scope note.
* @param key - AES key bytes.
* @param nonce - 12-byte nonce.
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.
*
* ```ts
* import { gcmsiv } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(12);
* const cipher = gcmsiv(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const gcmsiv: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
blockSize: number;
nonceLength: number;
tagLength: number;
varSizeNonce: true;
}>;
declare function encryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
declare function decryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
/**
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
* Reduces block size from 16 to 8 bytes.
* Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.
* 8-byte inputs use aeskwp.
* Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.
* For padded version, use aeskwp.
* See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.
* @param kek - AES key-encryption key.
* @returns Key-wrap cipher instance.
* As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per
* instance.
* @example
* Wraps a 128-bit content-encryption key with a fresh key-encryption key.
*
* ```ts
* import { aeskw } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const kek = randomBytes(16);
* const cek = randomBytes(16);
* const wrap = aeskw(kek);
* wrap.encrypt(cek);
* ```
*/
export declare const aeskw: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
blockSize: number;
}>;
/**
* AES-KW, but with padding and allows random keys.
* Uses the RFC 5649 alternative initial value; the second u32 stores the
* 32-bit MLI in network order.
* Wrapped ciphertext must be at least 16 bytes; malformed lengths are
* rejected during AIV/padding checks.
* See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.
* @param kek - AES key-encryption key.
* @returns Padded key-wrap cipher instance.
* @example
* Wraps a short key blob using the padded variant and a fresh key-encryption key.
*
* ```ts
* import { aeskwp } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const kek = randomBytes(16);
* const wrap = aeskwp(kek);
* wrap.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const aeskwp: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
blockSize: number;
}>;
declare class _AesCtrDRBG implements PRG {
readonly blockLen: number;
private key;
private nonce;
private state;
private reseedCnt;
constructor(keyLen: number, seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>);
private update;
addEntropy(seed: TArg<Uint8Array>, info?: TArg<Uint8Array>): void;
randomBytes(len: number, info?: TArg<Uint8Array>): TRet<Uint8Array>;
clean(): void;
}
/**
* Factory for AES-CTR DRBG instances.
* @param seed - Initial entropy input.
* @param personalization - Optional personalization string mixed into the state.
* @returns Seeded AES-CTR DRBG instance.
*/
export type AesCtrDrbg = (seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>) => TRet<_AesCtrDRBG>;
/**
* AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* @param seed - Initial 32-byte entropy input.
* @param personalization - Optional personalization string.
* @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
* @example
* Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
*
* ```ts
* import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const prg = rngAesCtrDrbg128(seed);
* prg.randomBytes(8);
* ```
*/
export declare const rngAesCtrDrbg128: TRet<AesCtrDrbg>;
/**
* AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* @param seed - Initial 48-byte entropy input.
* @param personalization - Optional personalization string.
* @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
* @example
* Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
*
* ```ts
* import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(48);
* const prg = rngAesCtrDrbg256(seed);
* prg.randomBytes(8);
* ```
*/
export declare const rngAesCtrDrbg256: TRet<AesCtrDrbg>;
/**
* Left-shift by one bit and conditionally XOR with 0x87:
* ```
* if MSB(L) is equal to 0
* then K1 := L << 1;
* else K1 := (L << 1) XOR const_Rb;
* ```
*
* Specs:
* {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}
*
* @returns modified `block` (for chaining)
*/
declare function dbl<T extends Uint8Array>(block: T): T;
/**
* `a XOR b`, running in-place on `a`.
* @param a left operand and output
* @param b right operand
* @returns `a` (for chaining)
*/
declare function xorBlock<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
/**
* xorend as defined in
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.
*
* ```
* leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)
* ```
*
* Mutates `a` in place so the left prefix stays untouched and only the
* rightmost `len(B)` bytes are xored with `b`.
*/
declare function xorend<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
/**
* Internal CMAC class.
*/
declare class _CMAC implements IHash2 {
readonly blockLen: number;
readonly outputLen: number;
private buffer;
private pos;
private finished;
private destroyed;
private k1;
private k2;
private x;
private xk;
constructor(key: TArg<Uint8Array>);
private process;
update(data: TArg<Uint8Array>): this;
digestInto(out: TArg<Uint8Array>): void;
digest(): Uint8ArrayBuffer;
destroy(): void;
}
/**
* AES-CMAC (Cipher-based Message Authentication Code).
* Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.
* @param msg - Message bytes to authenticate.
* @param key - AES key bytes.
* @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as
* the other keyed helpers in this repo, including `blockLen`,
* `outputLen`, `digestInto()` and `destroy()`.
* @example
* Authenticates a message with AES-CMAC and a fresh key.
*
* ```ts
* import { cmac } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* cmac(new Uint8Array(), key);
* ```
*/
export declare const cmac: TRet<CMac<_CMAC>>;
/**
* S2V (Synthetic Initialization Vector) function as described in
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.
*
* ```
* S2V(K, S1, ..., Sn) {
* if n = 0 then
* return V = AES-CMAC(K, <one>)
* fi
* D = AES-CMAC(K, <zero>)
* for i = 1 to n-1 do
* D = dbl(D) xor AES-CMAC(K, Si)
* done
* if len(Sn) >= 128 then
* T = Sn xorend D
* else
* T = dbl(D) xor pad(Sn)
* fi
* return V = AES-CMAC(K, T)
* }
* ```
*
* S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.
* The S2V function is used to generate a synthetic IV for AES-SIV.
*
* @param key - AES key (128, 192, or 256 bits)
* @param strings - Array of byte arrays to process
* @returns 128-bit synthetic IV
*/
declare function s2v(key: TArg<Uint8Array>, strings: TArg<Uint8Array[]>): TRet<Uint8Array>;
/**
* Use `gcmsiv` or `aessiv`.
* @returns Never; always throws with the migration hint.
* @throws If called; `siv()` is a removed v1 alias. {@link Error}
* @example
* `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.
*
* ```ts
* import { gcmsiv } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(12);
* const cipher = gcmsiv(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const siv: () => never;
/**
* **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption
* Nonce is derived from the plaintext and AAD using the S2V function.
* Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by
* passing the nonce as the final AAD component before the plaintext.
* See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.
* @param key - 32-byte, 48-byte, or 64-byte key.
* @param AAD - Additional authenticated data chunks (up to 126).
* @returns AEAD cipher instance.
* @example
* Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.
*
* ```ts
* import { aessiv } from '@noble/ciphers/aes.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const cipher = aessiv(key);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const aessiv: TRet<((key: TArg<Uint8Array>, ...AAD: TArg<Uint8Array[]>) => Cipher) & {
blockSize: number;
tagLength: number;
}>;
/**
* Unsafe low-level internal methods. May change at any time.
* Callers are expected to use reviewed expanded-key outputs, pass mutable and
* aligned 16-byte blocks where required, and treat several helpers as in-place
* mutations of their input buffers or counters.
*/
export declare const unsafe: {
expandKeyLE: typeof expandKeyLE;
expandKeyDecLE: typeof expandKeyDecLE;
encrypt: typeof encrypt;
decrypt: typeof decrypt;
encryptBlock: typeof encryptBlock;
decryptBlock: typeof decryptBlock;
ctrCounter: typeof ctrCounter;
ctr32: typeof ctr32;
dbl: typeof dbl;
xorBlock: typeof xorBlock;
xorend: typeof xorend;
s2v: typeof s2v;
};
export declare const __TESTS: {
incBytes: typeof incBytes;
};
export {};
//# sourceMappingURL=aes.d.ts.map
+1
View File
File diff suppressed because one or more lines are too long
+1765
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
+249
View File
@@ -0,0 +1,249 @@
/**
* ChaCha stream cipher, released
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
* It was standardized in
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
* is now used in TLS 1.3.
*
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
* randomly-generated nonces.
*
* Check out
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
* {@link https://cr.yp.to/chacha.html | website}.
*
* @module
*/
import { type XorPRG } from './_arx.ts';
import { type ARXCipher, type CipherWithOutput, type TArg, type TRet, type XorStream } from './utils.ts';
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
declare const chachaCore_small: typeof chachaCore;
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
declare function chachaCore(s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds?: number): void;
/**
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
* Algorithmically identical to `hchacha_small`, but this exported path
* normalizes word order on big-endian hosts.
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
* @param s - Sigma constants as 32-bit words.
* @param k - Key words.
* @param i - Nonce-prefix words.
* @param out - Output buffer for the derived subkey.
* @example
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
*
* ```ts
* const sigma = new Uint32Array(4);
* const key = new Uint32Array(8);
* const nonce = new Uint32Array(4);
* const out = new Uint32Array(8);
* hchacha(sigma, key, nonce, out);
* ```
*/
export declare function hchacha(s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>): void;
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
* near `MAX_COUNTER` for the full counter-policy rationale.
* @param key - 16-byte or 32-byte key.
* @param nonce - 8-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
*
* ```ts
* import { chacha20orig } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(8);
* chacha20orig(key, nonce, new Uint8Array(4));
* ```
*/
export declare const chacha20orig: TRet<XorStream>;
/**
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
*
* ```ts
* import { chacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha20(key, nonce, new Uint8Array(4));
* ```
*/
export declare const chacha20: TRet<XorStream>;
/**
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
* near `MAX_COUNTER` for the full counter-policy rationale.
* @param key - 32-byte key.
* @param nonce - 24-byte extended nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
*
* ```ts
* import { xchacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* xchacha20(key, nonce, new Uint8Array(4));
* ```
*/
export declare const xchacha20: TRet<XorStream>;
/**
* Reduced 8-round chacha, described in original paper.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
*
* ```ts
* import { chacha8 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha8(key, nonce, new Uint8Array(4));
* ```
*/
export declare const chacha8: TRet<XorStream>;
/**
* Reduced 12-round chacha, described in original paper.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
*
* ```ts
* import { chacha12 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha12(key, nonce, new Uint8Array(4));
* ```
*/
export declare const chacha12: TRet<XorStream>;
export declare const __TESTS: {
chachaCore_small: typeof chachaCore_small;
chachaCore: typeof chachaCore;
};
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them, but it's hard because of authKey:
* In salsa20, authKey changes position in salsa stream.
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
*/
export declare const _poly1305_aead: (xorStream: TArg<XorStream>) => (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => CipherWithOutput;
/**
* ChaCha20-Poly1305 from RFC 8439.
*
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XChaCha instead.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with a fresh key and nonce.
*
* ```ts
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* const cipher = chacha20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const chacha20poly1305: TRet<ARXCipher>;
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
*
* ```ts
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const cipher = xchacha20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const xchacha20poly1305: TRet<ARXCipher>;
/**
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
* only 32 random bytes are mixed into the 40-byte state.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
* @example
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
*
* ```ts
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const prg = rngChacha20(seed);
* prg.randomBytes(8);
* ```
*/
export declare const rngChacha20: TRet<XorPRG>;
/**
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* Faster than `rngChacha20`.
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
* only 32 random bytes are mixed into the 44-byte state.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
* @example
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
*
* ```ts
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const prg = rngChacha8(seed);
* prg.randomBytes(8);
* ```
*/
export declare const rngChacha8: TRet<XorPRG>;
export {};
//# sourceMappingURL=chacha.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"chacha.d.ts","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,KAAK,MAAM,EAAiC,MAAM,WAAW,CAAC;AAEvE,OAAO,EACL,KAAK,SAAS,EACd,KAAK,gBAAgB,EACrB,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EASf,MAAM,YAAY,CAAC;AAkEpB,sFAAsF;AAEtF,QAAA,MAAM,gBAAgB,EAAE,OAAO,UAE8C,CAAC;AAK9E,gFAAgF;AAEhF,iBAAS,UAAU,CACjB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,SAAK,GACjH,IAAI,CA6DN;AACD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,wBAAgB,OAAO,CACrB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CAqDN;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,YAAY,EAAE,IAAI,CAAC,SAAS,CAIvC,CAAC;AACH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,SAAS,CAKpC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAIlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAGH,eAAO,MAAM,OAAO,EAAE;IACpB,gBAAgB,EAAE,OAAO,gBAAgB,CAAC;IAC1C,UAAU,EAAE,OAAO,UAAU,CAAC;CACmC,CAAC;AA0CpE;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GACxB,WAAW,IAAI,CAAC,SAAS,CAAC,MAC1B,KAAK,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC,UAAU,CAAC,KAAG,gBA+CzE,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAG5C,CAAC;AACF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAG7C,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,WAAW,EAAE,IAAI,CAAC,MAAM,CAAsD,CAAC;AAC5F;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,MAAM,CAAkD,CAAC"}
+575
View File
@@ -0,0 +1,575 @@
/**
* ChaCha stream cipher, released
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
* It was standardized in
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
* is now used in TLS 1.3.
*
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
* randomly-generated nonces.
*
* Check out
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
* {@link https://cr.yp.to/chacha.html | website}.
*
* @module
*/
import { createCipher, createPRG, rotl } from "./_arx.js";
import { poly1305 } from "./_poly1305.js";
import { abytes, clean, equalBytes, getOutput, swap8IfBE, swap32IfBE, u64Lengths, wrapCipher, } from "./utils.js";
/**
* ChaCha core function. It is implemented twice:
* 1. Simple loop (chachaCore_small, hchacha_small)
* 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read
* The specific implementation is selected in `createCipher` below.
*/
/** RFC 8439 §2.1 quarter round on words a, b, c, d. */
// prettier-ignore
function chachaQR(x, a, b, c, d) {
x[a] = (x[a] + x[b]) | 0;
x[d] = rotl(x[d] ^ x[a], 16);
x[c] = (x[c] + x[d]) | 0;
x[b] = rotl(x[b] ^ x[c], 12);
x[a] = (x[a] + x[b]) | 0;
x[d] = rotl(x[d] ^ x[a], 8);
x[c] = (x[c] + x[d]) | 0;
x[b] = rotl(x[b] ^ x[c], 7);
}
/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */
function chachaRound(x, rounds = 20) {
for (let r = 0; r < rounds; r += 2) {
// RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds.
chachaQR(x, 0, 4, 8, 12);
chachaQR(x, 1, 5, 9, 13);
chachaQR(x, 2, 6, 10, 14);
chachaQR(x, 3, 7, 11, 15);
chachaQR(x, 0, 5, 10, 15);
chachaQR(x, 1, 6, 11, 12);
chachaQR(x, 2, 7, 8, 13);
chachaQR(x, 3, 4, 9, 14);
}
}
// Shared scratch for the auditability-only helper below; only the test-only
// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.
const ctmp = /* @__PURE__ */ new Uint32Array(16);
/** Small version of chacha without loop unrolling. Unused, provided for auditability. */
// prettier-ignore
function chacha(s, k, i, out, isHChacha = true, rounds = 20) {
// `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block
// function or the full 128-bit nonce prefix for the HChaCha subkey path.
// Create initial array using common pattern
const y = Uint32Array.from([
s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k"
k[0], k[1], k[2], k[3], // Key Key Key Key
k[4], k[5], k[6], k[7], // Key Key Key Key
i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce
]);
const x = ctmp;
x.set(y);
chachaRound(x, rounds);
// HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha
// block path adds the original state word-by-word.
if (isHChacha) {
const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];
for (let i = 0; i < 8; i++)
out[i] = x[xindexes[i]];
}
else {
for (let i = 0; i < 16; i++)
out[i] = (y[i] + x[i]) | 0;
}
}
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
// @ts-ignore
const chachaCore_small = (s, k, n, out, cnt, rounds) =>
// Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().
chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);
/** Identical to `hchacha`. Unused. */
// @ts-ignore
const hchacha_small = chacha;
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
// prettier-ignore
function chachaCore(s, k, n, out, cnt, rounds = 20) {
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k"
y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key
y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key
y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce
// Save state to temporary variables
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
for (let r = 0; r < rounds; r += 2) {
x00 = (x00 + x04) | 0;
x12 = rotl(x12 ^ x00, 16);
x08 = (x08 + x12) | 0;
x04 = rotl(x04 ^ x08, 12);
x00 = (x00 + x04) | 0;
x12 = rotl(x12 ^ x00, 8);
x08 = (x08 + x12) | 0;
x04 = rotl(x04 ^ x08, 7);
x01 = (x01 + x05) | 0;
x13 = rotl(x13 ^ x01, 16);
x09 = (x09 + x13) | 0;
x05 = rotl(x05 ^ x09, 12);
x01 = (x01 + x05) | 0;
x13 = rotl(x13 ^ x01, 8);
x09 = (x09 + x13) | 0;
x05 = rotl(x05 ^ x09, 7);
x02 = (x02 + x06) | 0;
x14 = rotl(x14 ^ x02, 16);
x10 = (x10 + x14) | 0;
x06 = rotl(x06 ^ x10, 12);
x02 = (x02 + x06) | 0;
x14 = rotl(x14 ^ x02, 8);
x10 = (x10 + x14) | 0;
x06 = rotl(x06 ^ x10, 7);
x03 = (x03 + x07) | 0;
x15 = rotl(x15 ^ x03, 16);
x11 = (x11 + x15) | 0;
x07 = rotl(x07 ^ x11, 12);
x03 = (x03 + x07) | 0;
x15 = rotl(x15 ^ x03, 8);
x11 = (x11 + x15) | 0;
x07 = rotl(x07 ^ x11, 7);
x00 = (x00 + x05) | 0;
x15 = rotl(x15 ^ x00, 16);
x10 = (x10 + x15) | 0;
x05 = rotl(x05 ^ x10, 12);
x00 = (x00 + x05) | 0;
x15 = rotl(x15 ^ x00, 8);
x10 = (x10 + x15) | 0;
x05 = rotl(x05 ^ x10, 7);
x01 = (x01 + x06) | 0;
x12 = rotl(x12 ^ x01, 16);
x11 = (x11 + x12) | 0;
x06 = rotl(x06 ^ x11, 12);
x01 = (x01 + x06) | 0;
x12 = rotl(x12 ^ x01, 8);
x11 = (x11 + x12) | 0;
x06 = rotl(x06 ^ x11, 7);
x02 = (x02 + x07) | 0;
x13 = rotl(x13 ^ x02, 16);
x08 = (x08 + x13) | 0;
x07 = rotl(x07 ^ x08, 12);
x02 = (x02 + x07) | 0;
x13 = rotl(x13 ^ x02, 8);
x08 = (x08 + x13) | 0;
x07 = rotl(x07 ^ x08, 7);
x03 = (x03 + x04) | 0;
x14 = rotl(x14 ^ x03, 16);
x09 = (x09 + x14) | 0;
x04 = rotl(x04 ^ x09, 12);
x03 = (x03 + x04) | 0;
x14 = rotl(x14 ^ x03, 8);
x09 = (x09 + x14) | 0;
x04 = rotl(x04 ^ x09, 7);
}
// RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.
let oi = 0;
out[oi++] = (y00 + x00) | 0;
out[oi++] = (y01 + x01) | 0;
out[oi++] = (y02 + x02) | 0;
out[oi++] = (y03 + x03) | 0;
out[oi++] = (y04 + x04) | 0;
out[oi++] = (y05 + x05) | 0;
out[oi++] = (y06 + x06) | 0;
out[oi++] = (y07 + x07) | 0;
out[oi++] = (y08 + x08) | 0;
out[oi++] = (y09 + x09) | 0;
out[oi++] = (y10 + x10) | 0;
out[oi++] = (y11 + x11) | 0;
out[oi++] = (y12 + x12) | 0;
out[oi++] = (y13 + x13) | 0;
out[oi++] = (y14 + x14) | 0;
out[oi++] = (y15 + x15) | 0;
}
/**
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
* Algorithmically identical to `hchacha_small`, but this exported path
* normalizes word order on big-endian hosts.
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
* @param s - Sigma constants as 32-bit words.
* @param k - Key words.
* @param i - Nonce-prefix words.
* @param out - Output buffer for the derived subkey.
* @example
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
*
* ```ts
* const sigma = new Uint32Array(4);
* const key = new Uint32Array(8);
* const nonce = new Uint32Array(4);
* const out = new Uint32Array(8);
* hchacha(sigma, key, nonce, out);
* ```
*/
// prettier-ignore
export function hchacha(s, k, i, out) {
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);
for (let r = 0; r < 20; r += 2) {
x00 = (x00 + x04) | 0;
x12 = rotl(x12 ^ x00, 16);
x08 = (x08 + x12) | 0;
x04 = rotl(x04 ^ x08, 12);
x00 = (x00 + x04) | 0;
x12 = rotl(x12 ^ x00, 8);
x08 = (x08 + x12) | 0;
x04 = rotl(x04 ^ x08, 7);
x01 = (x01 + x05) | 0;
x13 = rotl(x13 ^ x01, 16);
x09 = (x09 + x13) | 0;
x05 = rotl(x05 ^ x09, 12);
x01 = (x01 + x05) | 0;
x13 = rotl(x13 ^ x01, 8);
x09 = (x09 + x13) | 0;
x05 = rotl(x05 ^ x09, 7);
x02 = (x02 + x06) | 0;
x14 = rotl(x14 ^ x02, 16);
x10 = (x10 + x14) | 0;
x06 = rotl(x06 ^ x10, 12);
x02 = (x02 + x06) | 0;
x14 = rotl(x14 ^ x02, 8);
x10 = (x10 + x14) | 0;
x06 = rotl(x06 ^ x10, 7);
x03 = (x03 + x07) | 0;
x15 = rotl(x15 ^ x03, 16);
x11 = (x11 + x15) | 0;
x07 = rotl(x07 ^ x11, 12);
x03 = (x03 + x07) | 0;
x15 = rotl(x15 ^ x03, 8);
x11 = (x11 + x15) | 0;
x07 = rotl(x07 ^ x11, 7);
x00 = (x00 + x05) | 0;
x15 = rotl(x15 ^ x00, 16);
x10 = (x10 + x15) | 0;
x05 = rotl(x05 ^ x10, 12);
x00 = (x00 + x05) | 0;
x15 = rotl(x15 ^ x00, 8);
x10 = (x10 + x15) | 0;
x05 = rotl(x05 ^ x10, 7);
x01 = (x01 + x06) | 0;
x12 = rotl(x12 ^ x01, 16);
x11 = (x11 + x12) | 0;
x06 = rotl(x06 ^ x11, 12);
x01 = (x01 + x06) | 0;
x12 = rotl(x12 ^ x01, 8);
x11 = (x11 + x12) | 0;
x06 = rotl(x06 ^ x11, 7);
x02 = (x02 + x07) | 0;
x13 = rotl(x13 ^ x02, 16);
x08 = (x08 + x13) | 0;
x07 = rotl(x07 ^ x08, 12);
x02 = (x02 + x07) | 0;
x13 = rotl(x13 ^ x02, 8);
x08 = (x08 + x13) | 0;
x07 = rotl(x07 ^ x08, 7);
x03 = (x03 + x04) | 0;
x14 = rotl(x14 ^ x03, 16);
x09 = (x09 + x14) | 0;
x04 = rotl(x04 ^ x09, 12);
x03 = (x03 + x04) | 0;
x14 = rotl(x14 ^ x03, 8);
x09 = (x09 + x14) | 0;
x04 = rotl(x04 ^ x09, 7);
}
// HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.
let oi = 0;
out[oi++] = x00;
out[oi++] = x01;
out[oi++] = x02;
out[oi++] = x03;
out[oi++] = x12;
out[oi++] = x13;
out[oi++] = x14;
out[oi++] = x15;
swap32IfBE(out);
}
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
* near `MAX_COUNTER` for the full counter-policy rationale.
* @param key - 16-byte or 32-byte key.
* @param nonce - 8-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
*
* ```ts
* import { chacha20orig } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(8);
* chacha20orig(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
allowShortKeys: true,
});
/**
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
*
* ```ts
* import { chacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha20(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
allowShortKeys: false,
});
/**
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
* near `MAX_COUNTER` for the full counter-policy rationale.
* @param key - 32-byte key.
* @param nonce - 24-byte extended nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
*
* ```ts
* import { xchacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* xchacha20(key, nonce, new Uint8Array(4));
* ```
*/
export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
allowShortKeys: false,
});
/**
* Reduced 8-round chacha, described in original paper.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
*
* ```ts
* import { chacha8 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha8(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/**
* Reduced 12-round chacha, described in original paper.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
*
* ```ts
* import { chacha12 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha12(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.
export const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });
// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.
const updatePadded = (h, msg) => {
h.update(msg);
const leftover = msg.length % 16;
if (leftover)
h.update(ZEROS16.subarray(leftover));
};
// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key
// generation only needs 32 zero bytes.
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
function computeTag(fn, key, nonce, ciphertext, AAD) {
if (AAD !== undefined)
abytes(AAD, undefined, 'AAD');
// RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,
// then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).
const authKey = fn(key, nonce, ZEROS32);
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
// Methods below can be replaced with
// return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)
const h = poly1305.create(authKey);
if (AAD)
updatePadded(h, AAD);
updatePadded(h, ciphertext);
h.update(lengths);
const res = h.digest();
clean(authKey, lengths);
return res;
}
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them, but it's hard because of authKey:
* In salsa20, authKey changes position in salsa stream.
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
*/
export const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
// This borrows caller key/nonce/AAD buffers by reference; mutating them after construction
// changes future encrypt/decrypt results.
const tagLength = 16;
return {
encrypt(plaintext, output) {
const plength = plaintext.length;
output = getOutput(plength + tagLength, output, false);
output.set(plaintext);
const oPlain = output.subarray(0, -tagLength);
// RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.
xorStream(key, nonce, oPlain, oPlain, 1);
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
output.set(tag, plength); // append tag
clean(tag);
return output;
},
decrypt(ciphertext, output) {
output = getOutput(ciphertext.length - tagLength, output, false);
const data = ciphertext.subarray(0, -tagLength);
const passedTag = ciphertext.subarray(-tagLength);
const tag = computeTag(xorStream, key, nonce, data, AAD);
// RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with
// the constant-time equalBytes() helper rather than decrypting speculative plaintext first.
if (!equalBytes(passedTag, tag)) {
clean(tag);
throw new Error('invalid tag');
}
output.set(ciphertext.subarray(0, -tagLength));
// Actual decryption
xorStream(key, nonce, output, output, 1); // start stream with i=1
clean(tag);
return output;
},
};
};
/**
* ChaCha20-Poly1305 from RFC 8439.
*
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XChaCha instead.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with a fresh key and nonce.
*
* ```ts
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* const cipher = chacha20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 },
/* @__PURE__ */ _poly1305_aead(chacha20));
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
*
* ```ts
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const cipher = xchacha20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 },
/* @__PURE__ */ _poly1305_aead(xchacha20));
/**
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
* only 32 random bytes are mixed into the 40-byte state.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
* @example
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
*
* ```ts
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const prg = rngChacha20(seed);
* prg.randomBytes(8);
* ```
*/
export const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);
/**
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* Faster than `rngChacha20`.
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
* only 32 random bytes are mixed into the 44-byte state.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
* @example
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
*
* ```ts
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const prg = rngChacha8(seed);
* prg.randomBytes(8);
* ```
*/
export const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);
//# sourceMappingURL=chacha.js.map
+1
View File
File diff suppressed because one or more lines are too long
+40
View File
@@ -0,0 +1,40 @@
import { type Cipher, type TArg, type TRet } from './utils.ts';
/**
* FPE-FF1 format-preserving encryption.
* @param radix - Alphabet size for each input digit.
* @param key - AES key bytes.
* @param tweak - Optional tweak bytes.
* @returns Encrypt/decrypt helpers over digit arrays.
* @example
* Encrypts decimal digits without changing their format, using a fresh AES key.
*
* ```ts
* import { FF1 } from '@noble/ciphers/ff1.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const ff1 = FF1(10, key);
* ff1.encrypt([1, 2, 3]);
* ```
*/
export declare function FF1(radix: number, key: TArg<Uint8Array>, tweak?: TArg<Uint8Array>): {
encrypt(x: number[]): number[];
decrypt(x: number[]): number[];
};
/**
* Binary FPE-FF1 wrapper over byte arrays.
* @param key - AES key bytes.
* @param tweak - Optional tweak bytes.
* @returns Encrypt/decrypt helpers over byte arrays.
* @example
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
*
* ```ts
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const ff1 = BinaryFF1(key);
* ff1.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare function BinaryFF1(key: TArg<Uint8Array>, tweak?: TArg<Uint8Array>): TRet<Cipher>;
//# sourceMappingURL=ff1.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ff1.d.ts","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":"AAMA,OAAO,EAML,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAqGpB;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,GAAG,CACjB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC;IAAE,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAAE,CAkCpE;AAsBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC,IAAI,CAAC,MAAM,CAAC,CAQd"}
+204
View File
@@ -0,0 +1,204 @@
/**
* FPE-FF1 (Format-preserving encryption algorithm) specified in
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}.
* @module
*/
import { unsafe } from "./aes.js";
import { abytes, anumber, bytesToNumberBE, clean, numberToBytesBE, } from "./utils.js";
// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file
// reuses the reviewed AES key schedule and single-block encryption helpers.
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
const { expandKeyLE, encryptBlock } = unsafe;
// Format-preserving encryption algorithm (FPE-FF1) specified in
// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}.
const BLOCK_LEN = 16;
function mod(a, b) {
const result = a % b;
return result >= 0 ? result : b + result;
}
function NUMradix(radix, data) {
let res = BigInt(0);
for (let i of data)
res = res * BigInt(radix) + BigInt(i);
return res;
}
function getRound(radix, key, tweak, x) {
if (radix > 2 ** 16 - 1)
throw new Error('invalid radix ' + radix);
// radix**minlen ≥ 100
const minLen = Math.ceil(Math.log(100) / Math.log(radix));
const maxLen = 2 ** 32 - 1;
// 2 ≤ minlen ≤ maxlen < 2**32
if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32)
throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32');
if (!Array.isArray(x))
throw new Error('invalid X');
if (x.length < minLen || x.length > maxLen)
throw new Error('X is outside minLen..maxLen bounds');
// SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail
// before NUMradix(...) or round splitting can reinterpret them as a different numeral string.
for (const i of x) {
if (!Number.isSafeInteger(i) || i < 0 || i >= radix)
throw new Error('invalid X: digit outside radix');
}
const u = Math.floor(x.length / 2);
const v = x.length - u;
const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8);
const d = 4 * Math.ceil(b / 4) + 4;
const padding = mod(-tweak.length - b - 1, 16);
// P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4.
const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]);
const view = new DataView(P.buffer);
// NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as
// 0x00 || uint16_be(radix).
view.setUint16(4, radix, false);
view.setUint32(8, x.length, false);
view.setUint32(12, tweak.length, false);
// Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b.
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
PQ.set(P);
clean(P);
PQ.set(tweak, P.length);
const xk = expandKeyLE(key);
const round = (A, B, i, decrypt = false) => {
// Q = ... || [i]1 || [NUMradix(B)]b.
PQ[PQ.length - b - 1] = i;
if (b)
PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b);
// NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128.
let r = new Uint8Array(16);
for (let j = 0; j < PQ.length / BLOCK_LEN; j++) {
for (let i = 0; i < BLOCK_LEN; i++)
r[i] ^= PQ[j * BLOCK_LEN + i];
encryptBlock(xk, r);
}
// Let S be the first d bytes of the following string of ⎡d/16⎤ blocks:
// R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16).
let s = Array.from(r);
for (let j = 1; s.length < d; j++) {
const block = numberToBytesBE(BigInt(j), 16);
for (let k = 0; k < BLOCK_LEN; k++)
block[k] ^= r[k];
s.push(...Array.from(encryptBlock(xk, block)));
}
let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d)));
s.fill(0);
if (decrypt)
y = -y;
const m = i % 2 === 0 ? u : v;
let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m));
// STR(radix, m, c)
const C = Array(m).fill(0);
for (let i = 0; i < m; i++, c /= BigInt(radix))
C[m - 1 - i] = Number(c % BigInt(radix));
A.fill(0);
A = B;
B = C;
return [A, B];
};
const destroy = () => {
clean(xk, PQ);
};
return { u, round, destroy };
}
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
/**
* FPE-FF1 format-preserving encryption.
* @param radix - Alphabet size for each input digit.
* @param key - AES key bytes.
* @param tweak - Optional tweak bytes.
* @returns Encrypt/decrypt helpers over digit arrays.
* @example
* Encrypts decimal digits without changing their format, using a fresh AES key.
*
* ```ts
* import { FF1 } from '@noble/ciphers/ff1.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const ff1 = FF1(10, key);
* ff1.encrypt([1, 2, 3]);
* ```
*/
export function FF1(radix, key, tweak = EMPTY_BUF) {
anumber(radix);
abytes(key);
abytes(tweak);
// This borrows caller key/tweak buffers by reference through the bound closure; mutating them
// after construction changes later encrypt/decrypt outputs.
const PQ = getRound.bind(null, radix, key, tweak);
return {
encrypt(x) {
const { u, round, destroy } = PQ(x);
let [A, B] = [x.slice(0, u), x.slice(u)];
for (let i = 0; i < 10; i++)
[A, B] = round(A, B, i);
destroy();
const res = A.concat(B);
A.fill(0);
B.fill(0);
return res;
},
decrypt(x) {
const { u, round, destroy } = PQ(x);
// The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm;
// the differences are in Step 6, where:
// 1) the order of the indices is reversed,
// 2) the roles of A and B are swapped
// 3) modular addition is replaced by modular subtraction, in Step 6vi.
let [B, A] = [x.slice(0, u), x.slice(u)];
for (let i = 9; i >= 0; i--)
[A, B] = round(A, B, i, true);
destroy();
const res = B.concat(A);
A.fill(0);
B.fill(0);
return res;
},
};
}
// Binary wrapper uses little-endian bit order within each byte so bit 0 stays
// in the first numeral slot for this library-defined byte-array surface.
const binLE = {
encode(bytes) {
const x = [];
for (let i = 0; i < bytes.length; i++) {
for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1)
x.push(tmp & 1);
}
return x;
},
decode(b) {
if (!Array.isArray(b) || b.length % 8)
throw new Error('Invalid binary string');
const res = new Uint8Array(b.length / 8);
for (let i = 0, j = 0; i < res.length; i++) {
res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3);
res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7);
}
return res;
},
};
/**
* Binary FPE-FF1 wrapper over byte arrays.
* @param key - AES key bytes.
* @param tweak - Optional tweak bytes.
* @returns Encrypt/decrypt helpers over byte arrays.
* @example
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
*
* ```ts
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const ff1 = BinaryFF1(key);
* ff1.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export function BinaryFF1(key, tweak = EMPTY_BUF) {
const ff1 = FF1(2, key, tweak);
return {
encrypt: (x) => binLE.decode(ff1.encrypt(binLE.encode(x))),
decrypt: (x) => binLE.decode(ff1.decrypt(binLE.encode(x))),
};
}
//# sourceMappingURL=ff1.js.map
+1
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""}
+27
View File
@@ -0,0 +1,27 @@
/**
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
* @example
```js
import { gcm, aessiv } from '@noble/ciphers/aes.js';
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
// Unauthenticated encryption: make sure to use HMAC or similar
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
// KW
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
// Utilities
import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js';
import { poly1305 } from '@noble/ciphers/_poly1305.js';
import { ghash, polyval } from '@noble/ciphers/_polyval.js';
```
* @module
*/
throw new Error('root module cannot be imported: import submodules instead. Check out README');
export {};
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}
+85
View File
@@ -0,0 +1,85 @@
{
"name": "@noble/ciphers",
"version": "2.2.0",
"description": "Audited & minimal JS implementation of Salsa20, ChaCha and AES",
"files": [
"src",
"*.js",
"*.js.map",
"*.d.ts",
"*.d.ts.map"
],
"devDependencies": {
"@paulmillr/jsbt": "0.5.0",
"@scure/base": "2.0.0",
"@types/node": "25.3.0",
"fast-check": "4.2.0",
"prettier": "3.6.2",
"typescript": "6.0.2"
},
"scripts": {
"bench": "node test/benchmark/noble.ts",
"bench:compare": "cd test/benchmark; npm install; node compare.ts",
"build": "tsc",
"build:release": "npx --no @paulmillr/jsbt esbuild test/build",
"check": "npm run check:readme && npm run check:treeshake && npm run check:jsdoc",
"check:readme": "npx --no @paulmillr/jsbt readme package.json",
"check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake",
"check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json",
"build:clean": "rm *.{js,js.map,d.ts,d.ts.map} 2> /dev/null",
"format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'",
"test": "node test/index.ts",
"test:bun": "bun test/index.ts",
"test:deno": "deno --allow-env --allow-read test/index.ts",
"test:node20": "cd test; npx tsc; node compiled/test/index.js",
"test:slow": "node test/crosstest.test.ts slow"
},
"exports": {
".": "./index.js",
"./_arx.js": "./_arx.js",
"./_poly1305.js": "./_poly1305.js",
"./_polyval.js": "./_polyval.js",
"./aes.js": "./aes.js",
"./chacha.js": "./chacha.js",
"./ff1.js": "./ff1.js",
"./salsa.js": "./salsa.js",
"./utils.js": "./utils.js",
"./webcrypto.js": "./webcrypto.js"
},
"engines": {
"node": ">= 20.19.0"
},
"keywords": [
"salsa20",
"chacha",
"aes",
"cryptography",
"crypto",
"noble",
"cipher",
"ciphers",
"xsalsa20",
"xchacha20",
"poly1305",
"xsalsa20poly1305",
"chacha20poly1305",
"xchacha20poly1305",
"secretbox",
"rijndael",
"siv",
"ff1"
],
"homepage": "https://paulmillr.com/noble/",
"funding": "https://paulmillr.com/funding/",
"repository": {
"type": "git",
"url": "git+https://github.com/paulmillr/noble-ciphers.git"
},
"type": "module",
"main": "index.js",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false,
"author": "Paul Miller (https://paulmillr.com)",
"license": "MIT"
}
+115
View File
@@ -0,0 +1,115 @@
import { type ARXCipher, type TArg, type TRet, type XorStream } from './utils.ts';
/**
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
* Identical to `hsalsa_small`.
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
* @param s - Sigma constants as 32-bit words.
* @param k - Key words.
* @param i - Nonce-prefix words.
* @param out - Output buffer for the derived subkey.
* @example
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
*
* ```ts
* const sigma = new Uint32Array(4);
* const key = new Uint32Array(8);
* const nonce = new Uint32Array(4);
* const out = new Uint32Array(8);
* hsalsa(sigma, key, nonce, out);
* ```
*/
export declare function hsalsa(s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>): void;
/**
* Salsa20 from original paper. 8-byte nonce.
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
* @param key - 16-byte or 32-byte key.
* @param nonce - 8-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
* the high word stays zero and the implementation still caps the public
* value to 32 bits.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
*
* ```ts
* import { salsa20 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(8);
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
* ```
*/
export declare const salsa20: TRet<XorStream>;
/**
* XSalsa20 extended-nonce salsa.
* With 24-byte nonce, it's safe to make it random (CSPRNG).
* @param key - 32-byte key.
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
* @param nonce - 24-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
*
* ```ts
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
* ```
*/
export declare const xsalsa20: TRet<XorStream>;
/**
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
* With 24-byte nonce, it's safe to make it random (CSPRNG).
* Also known as `secretbox` from libsodium / nacl.
* No AAD input is supported here. Caller-provided `output` buffers for
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
* implementation uses a 32-byte leading scratch area before returning `+16`.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
*
* ```ts
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const cipher = xsalsa20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const xsalsa20poly1305: TRet<ARXCipher>;
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
* for `crypto_box`.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @returns Wrapper with `seal()` and `open()` helpers.
* @example
* Uses the libsodium-style `seal()` and `open()` wrapper.
*
* ```ts
* import { secretbox } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const box = secretbox(key, nonce);
* box.seal(new Uint8Array([1, 2, 3]));
* ```
*/
export declare function secretbox(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>): TRet<{
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
}>;
//# sourceMappingURL=salsa.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"salsa.d.ts","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":"AAqBA,OAAO,EAQL,KAAK,SAAS,EAEd,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAuHpB;;;;;;;;;;;;;;;;;;GAkBG;AAEH,wBAAgB,MAAM,CACpB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CA8BN;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAGlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAGnC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAwD5C,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,GACtB,IAAI,CAAC;IACN,IAAI,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IACnF,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;CACrF,CAAC,CAMD"}
+371
View File
@@ -0,0 +1,371 @@
/**
* Salsa20 stream cipher, released in 2005.
* Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
* which are hard to implement in a constant-time manner.
* Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
*
* - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20},
* extended-nonce
* variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits,
* and became safe to be picked at random.
* - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
* We provide the alias and corresponding seal / open methods.
* "crypto_box" and "sealedbox" are available in package
* {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}.
* - Check out
* {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF}
* and {@link https://cr.yp.to/snuffle.html | website}.
* @module
*/
import { createCipher, rotl } from "./_arx.js";
import { poly1305 } from "./_poly1305.js";
import { abytes, clean, equalBytes, getOutput, swap32IfBE, swap8IfBE, wrapCipher, } from "./utils.js";
/**
* Salsa20 core function. It is implemented twice:
* 1. Simple loop (salsaCore_small, hsalsa_small)
* 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read
* The specific implementation is selected in `createCipher` below.
* Performance numbers for 1MB inputs:
* * default x 779 ops/sec @ 1ms/op
* * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op
* * small x 132 ops/sec @ 7ms/op
*/
/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */
function salsaQR(x, a, b, c, d) {
x[b] ^= rotl((x[a] + x[d]) | 0, 7);
x[c] ^= rotl((x[b] + x[a]) | 0, 9);
x[d] ^= rotl((x[c] + x[b]) | 0, 13);
x[a] ^= rotl((x[d] + x[c]) | 0, 18);
}
/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */
function salsaRound(x, rounds = 20) {
for (let r = 0; r < rounds; r += 2) {
salsaQR(x, 0, 4, 8, 12);
salsaQR(x, 5, 9, 13, 1);
salsaQR(x, 10, 14, 2, 6);
salsaQR(x, 15, 3, 7, 11);
salsaQR(x, 0, 1, 2, 3);
salsaQR(x, 5, 6, 7, 4);
salsaQR(x, 10, 11, 8, 9);
salsaQR(x, 15, 12, 13, 14);
}
}
// Shared scratch for the unused auditability helper below; it would be
// non-reentrant under overlapping/nested calls, but current code doesn't invoke it.
const stmp = /* @__PURE__ */ new Uint32Array(16);
/** Small version of salsa without loop unrolling. Unused, provided for auditability. */
// prettier-ignore
function salsa(s, k, i, out, isHSalsa = true, rounds = 20) {
// Create initial array using common pattern
const y = Uint32Array.from([
s[0], k[0], k[1], k[2], // "expa" Key Key Key
k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce
i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key
k[5], k[6], k[7], s[3], // Key Key Key "te k"
]);
const x = stmp;
x.set(y);
// const x = y.slice();
salsaRound(x, rounds);
// hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state.
if (isHSalsa) {
const xindexes = [0, 5, 10, 15, 6, 7, 8, 9];
for (let i = 0; i < 8; i++)
out[i] = x[xindexes[i]];
}
else {
for (let i = 0; i < 16; i++)
out[i] = (y[i] + x[i]) | 0;
}
}
/** Identical to `salsaCore`. Unused. */
// @ts-ignore
const salsaCore_small = (s, k, n, out, cnt, rounds) => salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds);
/** Identical to `hsalsa`. Unused. */
// @ts-ignore
const hsalsa_small = salsa;
/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */
// prettier-ignore
function salsaCore(s, k, n, out, cnt, rounds = 20) {
// Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero.
// Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}.
let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key
y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce
y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key
y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k"
// Save state to temporary variables
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
for (let r = 0; r < rounds; r += 2) {
x04 ^= rotl(x00 + x12 | 0, 7);
x08 ^= rotl(x04 + x00 | 0, 9);
x12 ^= rotl(x08 + x04 | 0, 13);
x00 ^= rotl(x12 + x08 | 0, 18);
x09 ^= rotl(x05 + x01 | 0, 7);
x13 ^= rotl(x09 + x05 | 0, 9);
x01 ^= rotl(x13 + x09 | 0, 13);
x05 ^= rotl(x01 + x13 | 0, 18);
x14 ^= rotl(x10 + x06 | 0, 7);
x02 ^= rotl(x14 + x10 | 0, 9);
x06 ^= rotl(x02 + x14 | 0, 13);
x10 ^= rotl(x06 + x02 | 0, 18);
x03 ^= rotl(x15 + x11 | 0, 7);
x07 ^= rotl(x03 + x15 | 0, 9);
x11 ^= rotl(x07 + x03 | 0, 13);
x15 ^= rotl(x11 + x07 | 0, 18);
x01 ^= rotl(x00 + x03 | 0, 7);
x02 ^= rotl(x01 + x00 | 0, 9);
x03 ^= rotl(x02 + x01 | 0, 13);
x00 ^= rotl(x03 + x02 | 0, 18);
x06 ^= rotl(x05 + x04 | 0, 7);
x07 ^= rotl(x06 + x05 | 0, 9);
x04 ^= rotl(x07 + x06 | 0, 13);
x05 ^= rotl(x04 + x07 | 0, 18);
x11 ^= rotl(x10 + x09 | 0, 7);
x08 ^= rotl(x11 + x10 | 0, 9);
x09 ^= rotl(x08 + x11 | 0, 13);
x10 ^= rotl(x09 + x08 | 0, 18);
x12 ^= rotl(x15 + x14 | 0, 7);
x13 ^= rotl(x12 + x15 | 0, 9);
x14 ^= rotl(x13 + x12 | 0, 13);
x15 ^= rotl(x14 + x13 | 0, 18);
}
// Write output
let oi = 0;
out[oi++] = (y00 + x00) | 0;
out[oi++] = (y01 + x01) | 0;
out[oi++] = (y02 + x02) | 0;
out[oi++] = (y03 + x03) | 0;
out[oi++] = (y04 + x04) | 0;
out[oi++] = (y05 + x05) | 0;
out[oi++] = (y06 + x06) | 0;
out[oi++] = (y07 + x07) | 0;
out[oi++] = (y08 + x08) | 0;
out[oi++] = (y09 + x09) | 0;
out[oi++] = (y10 + x10) | 0;
out[oi++] = (y11 + x11) | 0;
out[oi++] = (y12 + x12) | 0;
out[oi++] = (y13 + x13) | 0;
out[oi++] = (y14 + x14) | 0;
out[oi++] = (y15 + x15) | 0;
}
/**
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
* Identical to `hsalsa_small`.
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
* @param s - Sigma constants as 32-bit words.
* @param k - Key words.
* @param i - Nonce-prefix words.
* @param out - Output buffer for the derived subkey.
* @example
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
*
* ```ts
* const sigma = new Uint32Array(4);
* const key = new Uint32Array(8);
* const nonce = new Uint32Array(4);
* const out = new Uint32Array(8);
* hsalsa(sigma, key, nonce, out);
* ```
*/
// prettier-ignore
export function hsalsa(s, k, i, out) {
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]), x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]), x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]), x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]);
for (let r = 0; r < 20; r += 2) {
x04 ^= rotl(x00 + x12 | 0, 7);
x08 ^= rotl(x04 + x00 | 0, 9);
x12 ^= rotl(x08 + x04 | 0, 13);
x00 ^= rotl(x12 + x08 | 0, 18);
x09 ^= rotl(x05 + x01 | 0, 7);
x13 ^= rotl(x09 + x05 | 0, 9);
x01 ^= rotl(x13 + x09 | 0, 13);
x05 ^= rotl(x01 + x13 | 0, 18);
x14 ^= rotl(x10 + x06 | 0, 7);
x02 ^= rotl(x14 + x10 | 0, 9);
x06 ^= rotl(x02 + x14 | 0, 13);
x10 ^= rotl(x06 + x02 | 0, 18);
x03 ^= rotl(x15 + x11 | 0, 7);
x07 ^= rotl(x03 + x15 | 0, 9);
x11 ^= rotl(x07 + x03 | 0, 13);
x15 ^= rotl(x11 + x07 | 0, 18);
x01 ^= rotl(x00 + x03 | 0, 7);
x02 ^= rotl(x01 + x00 | 0, 9);
x03 ^= rotl(x02 + x01 | 0, 13);
x00 ^= rotl(x03 + x02 | 0, 18);
x06 ^= rotl(x05 + x04 | 0, 7);
x07 ^= rotl(x06 + x05 | 0, 9);
x04 ^= rotl(x07 + x06 | 0, 13);
x05 ^= rotl(x04 + x07 | 0, 18);
x11 ^= rotl(x10 + x09 | 0, 7);
x08 ^= rotl(x11 + x10 | 0, 9);
x09 ^= rotl(x08 + x11 | 0, 13);
x10 ^= rotl(x09 + x08 | 0, 18);
x12 ^= rotl(x15 + x14 | 0, 7);
x13 ^= rotl(x12 + x15 | 0, 9);
x14 ^= rotl(x13 + x12 | 0, 13);
x15 ^= rotl(x14 + x13 | 0, 18);
}
let oi = 0;
// XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material.
out[oi++] = x00;
out[oi++] = x05;
out[oi++] = x10;
out[oi++] = x15;
out[oi++] = x06;
out[oi++] = x07;
out[oi++] = x08;
out[oi++] = x09;
swap32IfBE(out);
}
/**
* Salsa20 from original paper. 8-byte nonce.
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
* @param key - 16-byte or 32-byte key.
* @param nonce - 8-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
* the high word stays zero and the implementation still caps the public
* value to 32 bits.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
*
* ```ts
* import { salsa20 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(8);
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
* ```
*/
export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/**
* XSalsa20 extended-nonce salsa.
* With 24-byte nonce, it's safe to make it random (CSPRNG).
* @param key - 32-byte key.
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
* @param nonce - 24-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
*
* ```ts
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
* ```
*/
export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/**
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
* With 24-byte nonce, it's safe to make it random (CSPRNG).
* Also known as `secretbox` from libsodium / nacl.
* No AAD input is supported here. Caller-provided `output` buffers for
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
* implementation uses a 32-byte leading scratch area before returning `+16`.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
*
* ```ts
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const cipher = xsalsa20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => {
// This borrows caller key/nonce buffers by reference; mutating them after construction changes
// later encrypt/decrypt outputs.
return {
encrypt(plaintext, output) {
// xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption.
// Unfortunately, makes it hard to separate tag calculation & encryption itself,
// because 32 bytes is half-block of 64-byte salsa.
// Need 32 extra bytes up front for the auth-key scratch area described above.
output = getOutput(plaintext.length + 32, output, false);
// output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext.
const authKey = output.subarray(0, 32);
const ciphPlaintext = output.subarray(32);
output.set(plaintext, 32);
// authKey is produced by xoring the first 32 bytes with zeros.
clean(authKey);
// output = stream ^ output; authKey = stream ^ zeros(32)
xsalsa20(key, nonce, output, output);
const tag = poly1305(ciphPlaintext, authKey);
output.set(tag, 16);
// Clean up auth-key remnants and the temporary tag copy.
clean(output.subarray(0, 16), tag);
// Return output[16..].
return output.subarray(16);
},
decrypt(ciphertext, output) {
// tmp part passed tag ciphertext
// [0..32] [32..48] [48..]
// Authenticate the ciphertext before decrypting it; on tag failure the scratch/output
// buffer may already contain copied ciphertext and derived auth-key material.
abytes(ciphertext);
output = getOutput(ciphertext.length + 32, output, false);
// output[0..32] is auth-key scratch, output[32..48] is passed tag,
// output[48..] is ciphertext then plaintext.
const tmp = output.subarray(0, 32);
const passedTag = output.subarray(32, 48);
const ciphPlaintext = output.subarray(48);
output.set(ciphertext, 32);
// authKey is produced by xoring the scratch area with zeros.
clean(tmp);
const authKey = xsalsa20(key, nonce, tmp, tmp);
const tag = poly1305(ciphPlaintext, authKey);
if (!equalBytes(passedTag, tag)) {
clean(output);
throw new Error('invalid tag');
}
// output = stream ^ output[16..]
xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
clean(tmp, passedTag, tag);
// Return output[48..], skipping zeroized output[0..48].
return ciphPlaintext;
},
};
});
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
* for `crypto_box`.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @returns Wrapper with `seal()` and `open()` helpers.
* @example
* Uses the libsodium-style `seal()` and `open()` wrapper.
*
* ```ts
* import { secretbox } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const box = secretbox(key, nonce);
* box.seal(new Uint8Array([1, 2, 3]));
* ```
*/
export function secretbox(key, nonce) {
const xs = xsalsa20poly1305(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt };
}
//# sourceMappingURL=salsa.js.map
+1
View File
File diff suppressed because one or more lines are too long
+499
View File
@@ -0,0 +1,499 @@
/**
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
RFC8439 requires multi-step cipher stream, where
authKey starts with counter: 0, actual msg with counter: 1.
For this, we need a way to re-use nonce / counter:
const counter = new Uint8Array(4);
chacha(..., counter, ...); // counter is now 1
chacha(..., counter, ...); // counter is now 2
This is complicated:
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
- Original papers don't allow mutating counters
- Counter overflow is undefined [^1]
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
- Caveat: Cannot be re-used through all cases:
- * chacha has (counter | nonce)
- * xchacha has (nonce16 | counter | nonce16)
- Idea B: separate nonce / counter and provide separate API for counter re-use
- Caveat: there are different counter sizes depending on an algorithm.
- salsa & chacha also differ in structures of key & sigma:
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
chacha: s(4) | k(8) | cnt(1) | nonce(3)
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
- Caveat: we can't re-use counter array
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
Current noble policy is strict non-wrap for the shared 32-bit counter path:
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
wrap back to zero.
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
* @module
*/
import {
type PRG,
type TArg,
type TRet,
type XorStream,
abool,
abytes,
anumber,
checkOpts,
clean,
copyBytes,
getOutput,
isAligned32,
isLE,
randomBytes,
swap32IfBE,
u32,
} from './utils.ts';
// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
// Non-ASCII input would not match UTF-8 `TextEncoder` output.
const encodeStr = (str: string) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
// kept for legacy allowShortKeys Salsa/ChaCha variants.
const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
/**
* Rotates a 32-bit word left.
* @param a - Input word.
* @param b - Rotation count in bits.
* @returns Rotated 32-bit word.
* @example
* Moves the top byte of `0x12345678` into the low byte position.
* ```ts
* rotl(0x12345678, 8);
* ```
*/
export function rotl(a: number, b: number): number {
return (a << b) | (a >>> (32 - b));
}
/**
* ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.
* @param sigma - Sigma constants for the selected cipher layout.
* @param key - Expanded key words.
* @param nonce - Nonce and counter words prepared for the round function.
* @param output - Output block written in place.
* @param counter - Block counter value.
* @param rounds - Optional round count override.
*/
export type CipherCoreFn = (
sigma: TArg<Uint32Array>,
key: TArg<Uint32Array>,
nonce: TArg<Uint32Array>,
output: TArg<Uint32Array>,
counter: number,
rounds?: number
) => void;
/**
* Nonce-extension function used by XChaCha and XSalsa.
* @param sigma - Sigma constants for the selected cipher layout.
* @param key - Expanded key words.
* @param input - Input nonce words used for subkey derivation.
* @param output - Output buffer written with the derived nonce words.
*/
export type ExtendNonceFn = (
sigma: TArg<Uint32Array>,
key: TArg<Uint32Array>,
input: TArg<Uint32Array>,
output: TArg<Uint32Array>
) => void;
/** ARX cipher options.
* * `allowShortKeys` for 16-byte keys
* * `counterLength` in bytes
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
* */
export type CipherOpts = {
/** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */
allowShortKeys?: boolean;
/** Optional nonce-expansion hook used by extended-nonce variants. */
extendNonceFn?: ExtendNonceFn;
/** Counter length in bytes inside the nonce/counter layout. */
counterLength?: number;
/** Whether the layout is `nonce|counter` instead of `counter|nonce`. */
counterRight?: boolean;
/** Number of core rounds to execute. */
rounds?: number;
};
// Salsa and Chacha block length is always 512-bit
const BLOCK_LEN = 64;
// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
const BLOCK_LEN32 = 16;
// Counter policy for the shared public `counter` argument:
// - RFC/IETF ChaCha20 uses a 32-bit counter.
// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
// counter state and carry into the next word.
// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
// boundary instead of carrying.
// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
// Noble intentionally throws instead of silently picking one wrap model for users. In the default
// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
// whatever wider carry / wrap policy they need on top.
const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
function runCipher(
core: TArg<CipherCoreFn>,
sigma: TArg<Uint32Array>,
key: TArg<Uint32Array>,
nonce: TArg<Uint32Array>,
data: TArg<Uint8Array>,
output: TArg<Uint8Array>,
counter: number,
rounds: number
): void {
const len = data.length;
const block = new Uint8Array(BLOCK_LEN);
const b32 = u32(block);
// Make sure that buffers aligned to 4 bytes
const isAligned = isLE && isAligned32(data) && isAligned32(output);
const d32 = isAligned ? u32(data) : U32_EMPTY;
const o32 = isAligned ? u32(output) : U32_EMPTY;
// RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
// truncating the final partial block instead of materializing the whole keystream.
if (!isLE) {
for (let pos = 0; pos < len; counter++) {
core(
sigma as TRet<Uint32Array>,
key as TRet<Uint32Array>,
nonce as TRet<Uint32Array>,
b32,
counter,
rounds
);
// RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
swap32IfBE(b32);
if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
const take = Math.min(BLOCK_LEN, len - pos);
for (let j = 0, posj; j < take; j++) {
posj = pos + j;
output[posj] = data[posj] ^ block[j];
}
pos += take;
}
return;
}
for (let pos = 0; pos < len; counter++) {
core(
sigma as TRet<Uint32Array>,
key as TRet<Uint32Array>,
nonce as TRet<Uint32Array>,
b32,
counter,
rounds
);
// See MAX_COUNTER policy note above: never silently wrap the shared public counter.
if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
const take = Math.min(BLOCK_LEN, len - pos);
// aligned to 4 bytes
if (isAligned && take === BLOCK_LEN) {
const pos32 = pos / 4;
if (pos % 4 !== 0) throw new Error('arx: invalid block position');
for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {
posj = pos32 + j;
o32[posj] = d32[posj] ^ b32[j];
}
pos += BLOCK_LEN;
continue;
}
for (let j = 0, posj; j < take; j++) {
posj = pos + j;
output[posj] = data[posj] ^ block[j];
}
pos += take;
}
}
/**
* Creates an ARX stream cipher from a 32-bit core permutation.
* Used internally to build the exported Salsa and ChaCha stream ciphers.
* @param core - Core function that fills one keystream block.
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
* @returns Stream cipher function over byte arrays.
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
*/
export function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream> {
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(
{ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },
opts
);
if (typeof core !== 'function') throw new Error('core must be a function');
anumber(counterLength);
anumber(rounds);
abool(counterRight);
abool(allowShortKeys);
return (
key: TArg<Uint8Array>,
nonce: TArg<Uint8Array>,
data: TArg<Uint8Array>,
output?: TArg<Uint8Array>,
counter = 0
): TRet<Uint8Array> => {
abytes(key, undefined, 'key');
abytes(nonce, undefined, 'nonce');
abytes(data, undefined, 'data');
const len = data.length;
// Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
// must match the logical result length exactly instead of returning an oversized workspace.
output = getOutput(len, output, false);
anumber(counter);
// See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
const toClean = [];
// Key & sigma
// key=16 -> sigma16, k=key|key
// key=32 -> sigma32, k=key
let l = key.length;
let k: Uint8Array;
let sigma: Uint32Array;
if (l === 32) {
// Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
// final clean(...) all mutate or wipe the temporary buffer in place.
toClean.push((k = copyBytes(key)));
sigma = sigma32_32;
} else if (l === 16 && allowShortKeys) {
k = new Uint8Array(32);
k.set(key);
k.set(key, 16);
sigma = sigma16_32;
toClean.push(k);
} else {
abytes(key, 32, 'arx key');
throw new Error('invalid key size');
// throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
}
// Nonce
// salsa20: 8 (8-byte counter)
// chacha20orig: 8 (8-byte counter)
// chacha20: 12 (4-byte counter)
// xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
// xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
// Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
// swap32IfBE(...) never mutates caller nonce bytes in place.
if (!isLE || !isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));
let k32 = u32(k);
// hsalsa & hchacha: handle extended nonce
if (extendNonceFn) {
if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);
const n16 = nonce.subarray(0, 16);
if (isLE) extendNonceFn(sigma as TRet<Uint32Array>, k32, u32(n16), k32);
else {
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
clean(sigmaRaw);
swap32IfBE(k32);
}
nonce = nonce.subarray(16);
} else if (!isLE) swap32IfBE(k32);
// Handle nonce counter
const nonceNcLen = 16 - counterLength;
if (nonceNcLen !== nonce.length)
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
// Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
// counter bytes, while Salsa/XSalsa append them after the nonce words.
if (nonceNcLen !== 12) {
const nc = new Uint8Array(12);
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
nonce = nc;
toClean.push(nonce);
}
const n32 = swap32IfBE(u32(nonce));
// Ensure temporary key/nonce copies are wiped even if the remaining
// runtime guard in runCipher(...) throws on counter overflow.
try {
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
return output as TRet<Uint8Array>;
} finally {
clean(...toClean);
}
};
}
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
export class _XorStreamPRG implements PRG {
readonly blockLen: number;
readonly keyLen: number;
readonly nonceLen: number;
private state: TRet<Uint8Array>;
private buf: TRet<Uint8Array>;
private key: TRet<Uint8Array>;
private nonce: TRet<Uint8Array>;
private pos: number;
private ctr: number;
private cipher: TArg<XorStream>;
constructor(
cipher: TArg<XorStream>,
blockLen: number,
keyLen: number,
nonceLen: number,
seed: TArg<Uint8Array>
) {
this.cipher = cipher;
this.blockLen = blockLen;
this.keyLen = keyLen;
this.nonceLen = nonceLen;
this.state = new Uint8Array(this.keyLen + this.nonceLen) as TRet<Uint8Array>;
this.reseed(seed);
this.ctr = 0;
this.pos = this.blockLen;
this.buf = new Uint8Array(this.blockLen) as TRet<Uint8Array>;
// Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
// inputs in place through these subarray views.
this.key = this.state.subarray(0, this.keyLen) as TRet<Uint8Array>;
this.nonce = this.state.subarray(this.keyLen) as TRet<Uint8Array>;
}
private reseed(seed: TArg<Uint8Array>) {
abytes(seed);
if (!seed || seed.length === 0) throw new Error('entropy required');
// Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
// keystream so buffered leftovers from the previous state are never reused.
for (let i = 0; i < seed.length; i++) this.state[i % this.state.length] ^= seed[i];
this.ctr = 0;
this.pos = this.blockLen;
}
addEntropy(seed: TArg<Uint8Array>): void {
// Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
abytes(seed);
if (seed.length === 0) throw new Error('entropy required');
// Re-key from the current stream first, then mix external entropy into the fresh key||nonce
// state through reseed() so stale buffered bytes are discarded.
this.state.set(this.randomBytes(this.state.length));
this.reseed(seed);
}
randomBytes(len: number): TRet<Uint8Array> {
anumber(len);
if (len === 0) return new Uint8Array(0) as TRet<Uint8Array>;
const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
// Preflight overflow so failed reads don't partially consume keystream
// and leave the PRG repeating blocks.
if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) throw new Error('arx: counter overflow');
const out = new Uint8Array(len);
let outPos = 0;
// `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
// ciphers then emit raw keystream bytes directly into those buffers.
// Serve buffered leftovers first so split reads stay identical to one larger read.
if (this.pos < this.blockLen) {
const take = Math.min(len, this.blockLen - this.pos);
out.set(this.buf.subarray(this.pos, this.pos + take), 0);
this.pos += take;
outPos += take;
if (outPos === len) return out as TRet<Uint8Array>; // fast path
}
// Full blocks directly to out
const full = Math.floor((len - outPos) / this.blockLen);
if (full > 0) {
const blockBytes = full * this.blockLen;
const b = out.subarray(outPos, outPos + blockBytes);
this.cipher(this.key, this.nonce, b as TRet<Uint8Array>, b as TRet<Uint8Array>, this.ctr);
this.ctr += full;
outPos += blockBytes;
}
// Save leftovers
const left = len - outPos;
if (left > 0) {
this.buf.fill(0);
// NOTE: cipher will handle overflow
this.cipher(
this.key,
this.nonce,
this.buf as TRet<Uint8Array>,
this.buf as TRet<Uint8Array>,
this.ctr++
);
out.set(this.buf.subarray(0, left), outPos);
this.pos = left;
}
return out as TRet<Uint8Array>;
}
// Clone seeds the new instance from this stream, so the source PRG advances too.
clone(): _XorStreamPRG {
return new _XorStreamPRG(
this.cipher,
this.blockLen,
this.keyLen,
this.nonceLen,
this.randomBytes(this.state.length)
);
}
// Zeroes the current state and leftover buffer, but does not make the instance unusable:
// Later reads first drain zeros from the cleared buffer and then continue
// from zero key||nonce state.
clean(): void {
this.pos = 0;
this.ctr = 0;
this.buf.fill(0);
this.state.fill(0);
}
}
/**
* PRG constructor backed by an ARX stream cipher.
* @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32
* random bytes are mixed in by default: larger states keep a zero tail, while smaller states
* wrap those bytes through `reseed()`'s XOR schedule.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
*/
export type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;
/**
* Creates a PRG constructor from a stream cipher.
* @param cipher - Stream cipher used to fill output blocks.
* @param blockLen - Keystream block length in bytes.
* @param keyLen - Internal key length in bytes.
* @param nonceLen - Internal nonce length in bytes.
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
* @example
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
* ```ts
* import { xchacha20 } from '@noble/ciphers/chacha.js';
* import { createPRG } from '@noble/ciphers/_arx.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const init = createPRG(xchacha20, 64, 32, 24);
* const prg = init(seed);
* prg.randomBytes(8);
* ```
*/
export const createPRG = (
cipher: TArg<XorStream>,
blockLen: number,
keyLen: number,
nonceLen: number
): TRet<XorPRG> => {
return ((seed: TArg<Uint8Array> = randomBytes(32)): TRet<_XorStreamPRG> =>
new _XorStreamPRG(
cipher,
blockLen,
keyLen,
nonceLen,
seed
) as TRet<_XorStreamPRG>) as TRet<XorPRG>;
};
+399
View File
@@ -0,0 +1,399 @@
/**
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
* is a fast and parallel secret-key message-authentication code suitable for
* a wide variety of applications. It was standardized in
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
*
* Polynomial MACs are not perfect for every situation:
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
* however, this would violate ciphertext indistinguishability:
* an attacker would know which key was used - so `HKDF(key, i)`
* could be used instead.
*
* Check out the {@link https://cr.yp.to/mac.html | original website}.
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
* @module
*/
// prettier-ignore
import {
abytes, aexists, aoutput, bytesToHex,
clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE,
wrapMacConstructor, type CMac, type IHash2, type TArg, type TRet
} from './utils.ts';
// Little-endian 2-byte load used by the Poly1305 limb decomposition.
function u8to16(a: TArg<Uint8Array>, i: number) {
return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
}
function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */
function poly1305_small(msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array> {
abytes(msg);
abytes(key, 32, 'key');
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5
const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
const s = bytesToNumberLE(key.subarray(16));
// Process by 16 byte chunks
let acc = BigInt(0);
for (let i = 0; i < msg.length; i += 16) {
const m = msg.subarray(i, i + 16);
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r.
const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));
acc = ((acc + n) * r) % POW_2_130_5;
}
const res = (acc + s) & POW_2_128_1;
// RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order.
return numberToBytesBE(res, 16).reverse() as TRet<Uint8Array>; // LE
}
// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.
// @ts-expect-error
function poly1305_computeTag_small(
authKey: TArg<Uint8Array>,
// AEAD trailer must already be the 16-byte length block:
// 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.
lengths: TArg<Uint8Array>,
ciphertext: TArg<Uint8Array>,
AAD?: TArg<Uint8Array>
): TRet<Uint8Array> {
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is
// AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.
const res = [];
const updatePadded2 = (msg: TArg<Uint8Array>) => {
res.push(msg);
const leftover = msg.length % 16;
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned
// inputs, else 16-(len%16) zero bytes.
if (leftover) res.push(new Uint8Array(16).slice(leftover));
};
if (AAD) updatePadded2(AAD);
updatePadded2(ciphertext);
res.push(lengths);
return poly1305_small(concatBytes(...res), authKey);
}
/**
* Incremental Poly1305 MAC state.
* Prefer `poly1305()` for one-shot use.
* @param key - 32-byte Poly1305 one-time key.
* @example
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
*
* ```ts
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const mac = new Poly1305(key);
* mac.update(new Uint8Array([1, 2, 3]));
* mac.digest();
* ```
*/
export class Poly1305 implements IHash2 {
readonly blockLen = 16;
readonly outputLen = 16;
private buffer = new Uint8Array(16);
private r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
private h = new Uint16Array(10);
private pad = new Uint16Array(8);
private pos = 0;
protected finished = false;
protected destroyed = false;
// Can be speed-up using BigUint64Array, at the cost of complexity
constructor(key: TArg<Uint8Array>) {
key = copyBytes(abytes(key, 32, 'key'));
const t0 = u8to16(key, 0);
const t1 = u8to16(key, 2);
const t2 = u8to16(key, 4);
const t3 = u8to16(key, 6);
const t4 = u8to16(key, 8);
const t5 = u8to16(key, 10);
const t6 = u8to16(key, 12);
const t7 = u8to16(key, 14);
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
// These masks unpack that clamped value into 13-bit limbs, while pad
// keeps the raw s half for finalize().
// {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
this.r[0] = t0 & 0x1fff;
this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
this.r[5] = (t4 >>> 1) & 0x1ffe;
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
this.r[9] = (t7 >>> 5) & 0x007f;
for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);
}
private process(data: TArg<Uint8Array>, offset: number, isLast = false) {
// RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
// bit to every full 16-byte block. The final partial block gets its
// explicit `1` byte during digestInto(), so `hibit` stays zero there.
const hibit = isLast ? 0 : 1 << 11;
const { h, r } = this;
const r0 = r[0];
const r1 = r[1];
const r2 = r[2];
const r3 = r[3];
const r4 = r[4];
const r5 = r[5];
const r6 = r[6];
const r7 = r[7];
const r8 = r[8];
const r9 = r[9];
const t0 = u8to16(data, offset + 0);
const t1 = u8to16(data, offset + 2);
const t2 = u8to16(data, offset + 4);
const t3 = u8to16(data, offset + 6);
const t4 = u8to16(data, offset + 8);
const t5 = u8to16(data, offset + 10);
const t6 = u8to16(data, offset + 12);
const t7 = u8to16(data, offset + 14);
let h0 = h[0] + (t0 & 0x1fff);
let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
let h9 = h[9] + ((t7 >>> 5) | hibit);
let c = 0;
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
c = d0 >>> 13;
d0 &= 0x1fff;
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
c += d0 >>> 13;
d0 &= 0x1fff;
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
c = d1 >>> 13;
d1 &= 0x1fff;
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
c += d1 >>> 13;
d1 &= 0x1fff;
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
c = d2 >>> 13;
d2 &= 0x1fff;
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
c += d2 >>> 13;
d2 &= 0x1fff;
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
c = d3 >>> 13;
d3 &= 0x1fff;
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
c += d3 >>> 13;
d3 &= 0x1fff;
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
c = d4 >>> 13;
d4 &= 0x1fff;
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
c += d4 >>> 13;
d4 &= 0x1fff;
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
c = d5 >>> 13;
d5 &= 0x1fff;
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
c += d5 >>> 13;
d5 &= 0x1fff;
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
c = d6 >>> 13;
d6 &= 0x1fff;
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
c += d6 >>> 13;
d6 &= 0x1fff;
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
c = d7 >>> 13;
d7 &= 0x1fff;
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
c += d7 >>> 13;
d7 &= 0x1fff;
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
c = d8 >>> 13;
d8 &= 0x1fff;
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
c += d8 >>> 13;
d8 &= 0x1fff;
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
c = d9 >>> 13;
d9 &= 0x1fff;
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
c += d9 >>> 13;
d9 &= 0x1fff;
c = ((c << 2) + c) | 0;
c = (c + d0) | 0;
d0 = c & 0x1fff;
c = c >>> 13;
d1 += c;
h[0] = d0;
h[1] = d1;
h[2] = d2;
h[3] = d3;
h[4] = d4;
h[5] = d5;
h[6] = d6;
h[7] = d7;
h[8] = d8;
h[9] = d9;
}
private finalize() {
const { h, pad } = this;
const g = new Uint16Array(10);
let c = h[1] >>> 13;
h[1] &= 0x1fff;
for (let i = 2; i < 10; i++) {
h[i] += c;
c = h[i] >>> 13;
h[i] &= 0x1fff;
}
h[0] += c * 5;
c = h[0] >>> 13;
h[0] &= 0x1fff;
h[1] += c;
c = h[1] >>> 13;
h[1] &= 0x1fff;
h[2] += c;
// RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
// to 16-bit words and adding the raw s half.
g[0] = h[0] + 5;
c = g[0] >>> 13;
g[0] &= 0x1fff;
for (let i = 1; i < 10; i++) {
g[i] = h[i] + c;
c = g[i] >>> 13;
g[i] &= 0x1fff;
}
g[9] -= 1 << 13;
let mask = (c ^ 1) - 1;
for (let i = 0; i < 10; i++) g[i] &= mask;
mask = ~mask;
for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];
h[0] = (h[0] | (h[1] << 13)) & 0xffff;
h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
let f = h[0] + pad[0];
h[0] = f & 0xffff;
for (let i = 1; i < 8; i++) {
f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
h[i] = f & 0xffff;
}
clean(g);
}
update(data: TArg<Uint8Array>): this {
aexists(this);
abytes(data);
data = copyBytes(data);
const { buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path: we have at least one block in input
if (take === blockLen) {
for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(buffer, 0, false);
this.pos = 0;
}
}
return this;
}
destroy(): void {
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
this.destroyed = true;
clean(this.h, this.r, this.buffer, this.pad);
}
digestInto(out: TArg<Uint8Array>): void {
aexists(this);
aoutput(out, this);
this.finished = true;
const { buffer, h } = this;
let { pos } = this;
if (pos) {
// RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
// single `0x01` byte and zero-fills the remaining bytes before the
// last multiplication step.
buffer[pos++] = 1;
for (; pos < 16; pos++) buffer[pos] = 0;
this.process(buffer, 0, true);
}
this.finalize();
let opos = 0;
for (let i = 0; i < 8; i++) {
out[opos++] = h[i] >>> 0;
out[opos++] = h[i] >>> 8;
}
}
digest(): TRet<Uint8Array> {
const { buffer, outputLen } = this;
this.digestInto(buffer);
// Copy out before destroy() zeroes the internal buffer.
const res = buffer.slice(0, outputLen);
this.destroy();
return res as TRet<Uint8Array>;
}
}
/** One-shot keyed hash helper with `.create()`. */
export type CHash = CMac<Poly1305>;
/**
* Poly1305 MAC from RFC 8439.
* @param msg - Message bytes to authenticate.
* @param key - 32-byte Poly1305 one-time key.
* @returns 16-byte authentication tag.
* @example
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
*
* ```ts
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* poly1305(new Uint8Array(), key);
* ```
*/
export const poly1305: TRet<CHash> = /* @__PURE__ */ wrapMacConstructor(
32,
(key: TArg<Uint8Array>) => new Poly1305(key)
);
+381
View File
@@ -0,0 +1,381 @@
/**
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
*
* Implemented in terms of GHash with conversion function for keys
* GCM GHASH from
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
* SIV from
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
*
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
*
* @module
*/
import {
abytes,
aexists,
aoutput,
clean,
copyBytes,
createView,
swap32IfBE,
swap8IfBE,
u32,
wrapMacConstructor,
type CMac,
type IHash2,
type TArg,
type TRet,
} from './utils.ts';
const BLOCK_SIZE = 16;
// TODO: rewrite
// temporary padding buffer
// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
const ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
const POLY = 0xe1;
// v = 2*v % POLY
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
// Montgomery ladder can multiply any field element with this doubling step;
// addition stays simple xor.
const mul2 = (s0: number, s1: number, s2: number, s3: number) => {
const hiBit = s3 & 1;
return {
s3: (s2 << 31) | (s3 >>> 1),
s2: (s1 << 31) | (s2 >>> 1),
s1: (s0 << 31) | (s1 >>> 1),
// NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
// 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
};
};
// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
const swapLE = (n: number) =>
(((n >>> 0) & 0xff) << 24) |
(((n >>> 8) & 0xff) << 16) |
(((n >>> 16) & 0xff) << 8) |
((n >>> 24) & 0xff) |
0;
// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
const swap8IfLE = (n: number) => swap8IfBE(swapLE(n));
/**
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
* @param k mutated in place
*/
export function _toGHASHKey(k: TArg<Uint8Array>): TRet<Uint8Array> {
// The input is the original POLYVAL key H; reverse() materializes
// RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
k.reverse();
const hiBit = k[15] & 1;
// k >>= 1
let carry = 0;
for (let i = 0; i < k.length; i++) {
const t = k[i];
k[i] = (t >>> 1) | carry;
carry = (t & 1) << 7;
}
k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
return k as TRet<Uint8Array>;
}
type Value = { s0: number; s1: number; s2: number; s3: number };
// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
const estimateWindow = (bytes: number) => {
if (bytes > 64 * 1024) return 8;
if (bytes > 1024) return 4;
return 2;
};
/**
* Incremental GHASH state for AES-GCM.
* @param key - 16-byte GHASH key.
* @param expectedLength - Expected message length for table sizing.
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
* use where AAD, payload, and length block are separate padded segments.
* @example
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
*
* ```ts
* import { GHASH } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const mac = new GHASH(key);
* mac.update(new Uint8Array(16));
* mac.digest();
* ```
*/
export class GHASH implements IHash2 {
readonly blockLen: number = BLOCK_SIZE;
readonly outputLen: number = BLOCK_SIZE;
protected s0 = 0;
protected s1 = 0;
protected s2 = 0;
protected s3 = 0;
protected finished = false;
protected destroyed = false;
protected t: Value[];
private W: number;
private windowSize: number;
// We select bits per window adaptively based on expectedLength
constructor(key: TArg<Uint8Array>, expectedLength?: number) {
abytes(key, 16, 'key');
key = copyBytes(key);
const kView = createView(key);
let k0 = kView.getUint32(0, false);
let k1 = kView.getUint32(4, false);
let k2 = kView.getUint32(8, false);
let k3 = kView.getUint32(12, false);
// generate table of doubled keys (half of montgomery ladder)
const doubles: Value[] = [];
for (let i = 0; i < 128; i++) {
doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
}
const W = estimateWindow(expectedLength || 1024);
if (![1, 2, 4, 8].includes(W))
throw new Error('ghash: invalid window size, expected 2, 4 or 8');
this.W = W;
const bits = 128; // always 128 bits;
const windows = bits / W;
const windowSize = (this.windowSize = 2 ** W);
const items: Value[] = [];
// Create precompute table for window of W bits
for (let w = 0; w < windows; w++) {
// truth table: 00, 01, 10, 11
for (let byte = 0; byte < windowSize; byte++) {
// prettier-ignore
let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
for (let j = 0; j < W; j++) {
const bit = (byte >>> (W - j - 1)) & 1;
if (!bit) continue;
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
}
items.push({ s0, s1, s2, s3 });
}
}
this.t = items;
}
protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void {
((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
const { W, t, windowSize } = this;
// prettier-ignore
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
const mask = (1 << W) - 1; // 2**W will kill performance.
let w = 0;
// NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
// so the lookup walk consumes each word byte-by-byte from
// least-significant to most-significant bits.
for (const num of [s0, s1, s2, s3]) {
for (let bytePos = 0; bytePos < 4; bytePos++) {
const byte = (num >>> (8 * bytePos)) & 0xff;
for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
const bit = (byte >>> (W * bitPos)) & mask;
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
w += 1;
}
}
}
this.s0 = o0;
this.s1 = o1;
this.s2 = o2;
this.s3 = o3;
}
update(data: TArg<Uint8Array>): this {
aexists(this);
abytes(data);
data = copyBytes(data);
const b32 = u32(data);
const blocks = Math.floor(data.length / BLOCK_SIZE);
const left = data.length % BLOCK_SIZE;
for (let i = 0; i < blocks; i++) {
this._updateBlock(
swap8IfBE(b32[i * 4 + 0]),
swap8IfBE(b32[i * 4 + 1]),
swap8IfBE(b32[i * 4 + 2]),
swap8IfBE(b32[i * 4 + 3])
);
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
// Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
// normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
this._updateBlock(
swap8IfBE(ZEROS32[0]),
swap8IfBE(ZEROS32[1]),
swap8IfBE(ZEROS32[2]),
swap8IfBE(ZEROS32[3])
);
clean(ZEROS32); // clean tmp buffer
}
return this;
}
destroy(): void {
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
this.destroyed = true;
const { t } = this;
// Wipe the key-derived precompute table; scalar accumulator words remain,
// but the destroyed guard blocks further use.
// clean precompute table
for (const elm of t) {
((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
}
}
digestInto(out: TArg<Uint8Array>): void {
aexists(this);
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
// 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
aoutput(out, this, true);
this.finished = true;
// NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
// `digestInto()` follows the relaxed `aoutput()` contract, so only
// out[0..15] may be touched.
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
swap32IfBE(o32);
}
digest(): TRet<Uint8Array> {
const res = new Uint8Array(BLOCK_SIZE);
this.digestInto(res);
// `res` is independent of internal state, so it stays valid after destroy() wipes the table.
this.destroy();
return res as TRet<Uint8Array>;
}
}
/**
* Incremental POLYVAL state for AES-SIV.
* @param key - 16-byte POLYVAL key.
* @param expectedLength - Expected message length for table sizing.
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
* independently to a 16-byte boundary before absorption.
* @example
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
*
* ```ts
* import { Polyval } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const mac = new Polyval(key);
* mac.update(new Uint8Array(16));
* mac.digest();
* ```
*/
export class Polyval extends GHASH {
constructor(key: TArg<Uint8Array>, expectedLength?: number) {
abytes(key);
// RFC 8452 Appendix A converts the POLYVAL key with
// `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
// mutates in place.
const ghKey = _toGHASHKey(copyBytes(key));
super(ghKey, expectedLength);
clean(ghKey);
}
update(data: TArg<Uint8Array>): this {
aexists(this);
abytes(data);
data = copyBytes(data);
const b32 = u32(data);
const left = data.length % BLOCK_SIZE;
const blocks = Math.floor(data.length / BLOCK_SIZE);
for (let i = 0; i < blocks; i++) {
// RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
// reverses the 32-bit word order in addition to the per-word byte swap.
this._updateBlock(
swap8IfLE(b32[i * 4 + 3]),
swap8IfLE(b32[i * 4 + 2]),
swap8IfLE(b32[i * 4 + 1]),
swap8IfLE(b32[i * 4 + 0])
);
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(
swap8IfLE(ZEROS32[3]),
swap8IfLE(ZEROS32[2]),
swap8IfLE(ZEROS32[1]),
swap8IfLE(ZEROS32[0])
);
clean(ZEROS32);
}
return this;
}
digestInto(out: TArg<Uint8Array>): void {
aexists(this);
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
// 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
aoutput(out, this, true);
this.finished = true;
// RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
// `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
const view = out.subarray(0, this.outputLen);
const { s0, s1, s2, s3 } = this;
const o32 = u32(view);
o32[0] = s0;
o32[1] = s1;
o32[2] = s2;
o32[3] = s3;
swap32IfBE(o32);
view.reverse();
}
}
/**
* GHash MAC for AES-GCM.
* @param msg - Message bytes to authenticate.
* @param key - 16-byte GHASH key.
* @returns 16-byte authentication tag.
* @example
* Authenticates a short message with GHASH and a fresh hash key.
*
* ```ts
* import { ghash } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* ghash(new Uint8Array(), key);
* ```
*/
export const ghash: TRet<CMac<GHASH, [expectedLength?: number]>> =
/* @__PURE__ */ wrapMacConstructor(
16,
(key: TArg<Uint8Array>, expectedLength?: number) => new GHASH(key, expectedLength),
(msg: TArg<Uint8Array>): [expectedLength?: number] => [msg.length]
);
/**
* POLYVAL MAC for AES-SIV.
* @param msg - Message bytes to authenticate.
* @param key - 16-byte POLYVAL key.
* @returns 16-byte authentication tag.
* @example
* Authenticates a short message with POLYVAL and a fresh hash key.
*
* ```ts
* import { polyval } from '@noble/ciphers/_polyval.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* polyval(new Uint8Array(), key);
* ```
*/
export const polyval: TRet<CMac<Polyval, [expectedLength?: number]>> =
/* @__PURE__ */ wrapMacConstructor(
16,
(key: TArg<Uint8Array>, expectedLength?: number) => new Polyval(key, expectedLength),
(msg: TArg<Uint8Array>): [expectedLength?: number] => [msg.length]
);
+2018
View File
File diff suppressed because it is too large Load Diff
+579
View File
@@ -0,0 +1,579 @@
/**
* ChaCha stream cipher, released
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
* It was standardized in
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
* is now used in TLS 1.3.
*
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
* randomly-generated nonces.
*
* Check out
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
* {@link https://cr.yp.to/chacha.html | website}.
*
* @module
*/
import { type XorPRG, createCipher, createPRG, rotl } from './_arx.ts';
import { poly1305 } from './_poly1305.ts';
import {
type ARXCipher,
type CipherWithOutput,
type TArg,
type TRet,
type XorStream,
abytes,
clean,
equalBytes,
getOutput,
swap8IfBE,
swap32IfBE,
u64Lengths,
wrapCipher,
} from './utils.ts';
/**
* ChaCha core function. It is implemented twice:
* 1. Simple loop (chachaCore_small, hchacha_small)
* 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read
* The specific implementation is selected in `createCipher` below.
*/
/** RFC 8439 §2.1 quarter round on words a, b, c, d. */
// prettier-ignore
function chachaQR(x: TArg<Uint32Array>, a: number, b: number, c: number, d: number) {
x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16);
x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12);
x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8);
x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7);
}
/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */
function chachaRound(x: TArg<Uint32Array>, rounds = 20) {
for (let r = 0; r < rounds; r += 2) {
// RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds.
chachaQR(x, 0, 4, 8, 12);
chachaQR(x, 1, 5, 9, 13);
chachaQR(x, 2, 6, 10, 14);
chachaQR(x, 3, 7, 11, 15);
chachaQR(x, 0, 5, 10, 15);
chachaQR(x, 1, 6, 11, 12);
chachaQR(x, 2, 7, 8, 13);
chachaQR(x, 3, 4, 9, 14);
}
}
// Shared scratch for the auditability-only helper below; only the test-only
// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.
const ctmp = /* @__PURE__ */ new Uint32Array(16);
/** Small version of chacha without loop unrolling. Unused, provided for auditability. */
// prettier-ignore
function chacha(
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>,
isHChacha: boolean = true, rounds: number = 20
): void {
// `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block
// function or the full 128-bit nonce prefix for the HChaCha subkey path.
// Create initial array using common pattern
const y = Uint32Array.from([
s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k"
k[0], k[1], k[2], k[3], // Key Key Key Key
k[4], k[5], k[6], k[7], // Key Key Key Key
i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce
]);
const x = ctmp;
x.set(y);
chachaRound(x, rounds);
// HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha
// block path adds the original state word-by-word.
if (isHChacha) {
const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];
for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];
} else {
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
}
}
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
// @ts-ignore
const chachaCore_small: typeof chachaCore = (s, k, n, out, cnt, rounds) =>
// Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().
chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);
/** Identical to `hchacha`. Unused. */
// @ts-ignore
const hchacha_small: typeof hchacha = chacha;
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
// prettier-ignore
function chachaCore(
s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds = 20
): void {
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k"
y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key
y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key
y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce
// Save state to temporary variables
let x00 = y00, x01 = y01, x02 = y02, x03 = y03,
x04 = y04, x05 = y05, x06 = y06, x07 = y07,
x08 = y08, x09 = y09, x10 = y10, x11 = y11,
x12 = y12, x13 = y13, x14 = y14, x15 = y15;
for (let r = 0; r < rounds; r += 2) {
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);
}
// RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.
let oi = 0;
out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;
out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;
out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;
out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;
out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;
out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;
out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;
out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;
}
/**
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
* Algorithmically identical to `hchacha_small`, but this exported path
* normalizes word order on big-endian hosts.
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
* @param s - Sigma constants as 32-bit words.
* @param k - Key words.
* @param i - Nonce-prefix words.
* @param out - Output buffer for the derived subkey.
* @example
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
*
* ```ts
* const sigma = new Uint32Array(4);
* const key = new Uint32Array(8);
* const nonce = new Uint32Array(4);
* const out = new Uint32Array(8);
* hchacha(sigma, key, nonce, out);
* ```
*/
// prettier-ignore
export function hchacha(
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>
): void {
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]),
x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]),
x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]),
x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);
for (let r = 0; r < 20; r += 2) {
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);
}
// HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.
let oi = 0;
out[oi++] = x00; out[oi++] = x01;
out[oi++] = x02; out[oi++] = x03;
out[oi++] = x12; out[oi++] = x13;
out[oi++] = x14; out[oi++] = x15;
swap32IfBE(out);
}
/**
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
* near `MAX_COUNTER` for the full counter-policy rationale.
* @param key - 16-byte or 32-byte key.
* @param nonce - 8-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
*
* ```ts
* import { chacha20orig } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(8);
* chacha20orig(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha20orig: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
allowShortKeys: true,
});
/**
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
*
* ```ts
* import { chacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha20(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
allowShortKeys: false,
});
/**
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
* near `MAX_COUNTER` for the full counter-policy rationale.
* @param key - 32-byte key.
* @param nonce - 24-byte extended nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
*
* ```ts
* import { xchacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* xchacha20(key, nonce, new Uint8Array(4));
* ```
*/
export const xchacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 8,
extendNonceFn: hchacha,
allowShortKeys: false,
});
/**
* Reduced 8-round chacha, described in original paper.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
*
* ```ts
* import { chacha8 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha8(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha8: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 8,
});
/**
* Reduced 12-round chacha, described in original paper.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
*
* ```ts
* import { chacha12 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* chacha12(key, nonce, new Uint8Array(4));
* ```
*/
export const chacha12: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
rounds: 12,
});
// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.
export const __TESTS: {
chachaCore_small: typeof chachaCore_small;
chachaCore: typeof chachaCore;
} = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });
// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.
const updatePadded = (h: ReturnType<typeof poly1305.create>, msg: TArg<Uint8Array>) => {
h.update(msg);
const leftover = msg.length % 16;
if (leftover) h.update(ZEROS16.subarray(leftover));
};
// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key
// generation only needs 32 zero bytes.
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
function computeTag(
fn: TArg<XorStream>,
key: TArg<Uint8Array>,
nonce: TArg<Uint8Array>,
ciphertext: TArg<Uint8Array>,
AAD?: TArg<Uint8Array>
): TRet<Uint8Array> {
if (AAD !== undefined) abytes(AAD, undefined, 'AAD');
// RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,
// then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).
const authKey = fn(
key as TRet<Uint8Array>,
nonce as TRet<Uint8Array>,
ZEROS32 as TRet<Uint8Array>
);
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
// Methods below can be replaced with
// return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)
const h = poly1305.create(authKey);
if (AAD) updatePadded(h, AAD);
updatePadded(h, ciphertext);
h.update(lengths);
const res = h.digest();
clean(authKey, lengths);
return res;
}
/**
* AEAD algorithm from RFC 8439.
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
* We could have composed them, but it's hard because of authKey:
* In salsa20, authKey changes position in salsa stream.
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
*/
export const _poly1305_aead =
(xorStream: TArg<XorStream>) =>
(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>): CipherWithOutput => {
// This borrows caller key/nonce/AAD buffers by reference; mutating them after construction
// changes future encrypt/decrypt results.
const tagLength = 16;
return {
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
const plength = plaintext.length;
output = getOutput(plength + tagLength, output, false);
output.set(plaintext);
const oPlain = output.subarray(0, -tagLength);
// RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.
xorStream(
key as TRet<Uint8Array>,
nonce as TRet<Uint8Array>,
oPlain as TRet<Uint8Array>,
oPlain as TRet<Uint8Array>,
1
);
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
output.set(tag, plength); // append tag
clean(tag);
return output as TRet<Uint8Array>;
},
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
output = getOutput(ciphertext.length - tagLength, output, false);
const data = ciphertext.subarray(0, -tagLength);
const passedTag = ciphertext.subarray(-tagLength);
const tag = computeTag(xorStream, key, nonce, data, AAD);
// RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with
// the constant-time equalBytes() helper rather than decrypting speculative plaintext first.
if (!equalBytes(passedTag, tag)) {
clean(tag);
throw new Error('invalid tag');
}
output.set(ciphertext.subarray(0, -tagLength));
// Actual decryption
xorStream(
key as TRet<Uint8Array>,
nonce as TRet<Uint8Array>,
output as TRet<Uint8Array>,
output as TRet<Uint8Array>,
1
); // start stream with i=1
clean(tag);
return output as TRet<Uint8Array>;
},
};
};
/**
* ChaCha20-Poly1305 from RFC 8439.
*
* Unsafe to use random nonces under the same key, due to collision chance.
* Prefer XChaCha instead.
* @param key - 32-byte key.
* @param nonce - 12-byte nonce.
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with a fresh key and nonce.
*
* ```ts
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(12);
* const cipher = chacha20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const chacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 12, tagLength: 16 },
/* @__PURE__ */ _poly1305_aead(chacha20)
);
/**
* XChaCha20-Poly1305 extended-nonce chacha.
*
* Can be safely used with random nonces (CSPRNG).
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @param AAD - Additional authenticated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
*
* ```ts
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const cipher = xchacha20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const xchacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
/* @__PURE__ */ _poly1305_aead(xchacha20)
);
/**
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
* only 32 random bytes are mixed into the 40-byte state.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
* @example
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
*
* ```ts
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const prg = rngChacha20(seed);
* prg.randomBytes(8);
* ```
*/
export const rngChacha20: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);
/**
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
* Faster than `rngChacha20`.
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
* only 32 random bytes are mixed into the 44-byte state.
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
* @example
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
*
* ```ts
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const seed = randomBytes(32);
* const prg = rngChacha8(seed);
* prg.randomBytes(8);
* ```
*/
export const rngChacha8: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);
+221
View File
@@ -0,0 +1,221 @@
/**
* FPE-FF1 (Format-preserving encryption algorithm) specified in
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}.
* @module
*/
import { unsafe } from './aes.ts';
import {
abytes,
anumber,
bytesToNumberBE,
clean,
numberToBytesBE,
type Cipher,
type TArg,
type TRet,
} from './utils.ts';
// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file
// reuses the reviewed AES key schedule and single-block encryption helpers.
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
const { expandKeyLE, encryptBlock } = unsafe;
// Format-preserving encryption algorithm (FPE-FF1) specified in
// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}.
const BLOCK_LEN = 16;
// FF1 step 6vi needs mathematical modulo in [0, b); JS `%` is remainder, so decrypt rounds must
// map negative intermediate values back into that range.
function mod(a: number, b: number): number;
function mod(a: bigint, b: bigint): bigint;
function mod(a: any, b: any): number | bigint {
const result = a % b;
return result >= 0 ? result : b + result;
}
function NUMradix(radix: number, data: number[]): bigint {
let res = BigInt(0);
for (let i of data) res = res * BigInt(radix) + BigInt(i);
return res;
}
function getRound(radix: number, key: TArg<Uint8Array>, tweak: TArg<Uint8Array>, x: number[]) {
if (radix > 2 ** 16 - 1) throw new Error('invalid radix ' + radix);
// radix**minlen ≥ 100
const minLen = Math.ceil(Math.log(100) / Math.log(radix));
const maxLen = 2 ** 32 - 1;
// 2 ≤ minlen ≤ maxlen < 2**32
if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32)
throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32');
if (!Array.isArray(x)) throw new Error('invalid X');
if (x.length < minLen || x.length > maxLen) throw new Error('X is outside minLen..maxLen bounds');
// SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail
// before NUMradix(...) or round splitting can reinterpret them as a different numeral string.
for (const i of x) {
if (!Number.isSafeInteger(i) || i < 0 || i >= radix)
throw new Error('invalid X: digit outside radix');
}
const u = Math.floor(x.length / 2);
const v = x.length - u;
const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8);
const d = 4 * Math.ceil(b / 4) + 4;
const padding = mod(-tweak.length - b - 1, 16);
// P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4.
const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]);
const view = new DataView(P.buffer);
// NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as
// 0x00 || uint16_be(radix).
view.setUint16(4, radix, false);
view.setUint32(8, x.length, false);
view.setUint32(12, tweak.length, false);
// Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b.
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
PQ.set(P);
clean(P);
PQ.set(tweak, P.length);
const xk = expandKeyLE(key);
const round = (A: number[], B: number[], i: number, decrypt = false) => {
// Q = ... || [i]1 || [NUMradix(B)]b.
PQ[PQ.length - b - 1] = i;
if (b) PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b);
// NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128.
let r = new Uint8Array(16);
for (let j = 0; j < PQ.length / BLOCK_LEN; j++) {
for (let i = 0; i < BLOCK_LEN; i++) r[i] ^= PQ[j * BLOCK_LEN + i];
encryptBlock(xk, r);
}
// Let S be the first d bytes of the following string of ⎡d/16⎤ blocks:
// R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16).
let s = Array.from(r);
for (let j = 1; s.length < d; j++) {
const block = numberToBytesBE(BigInt(j), 16);
for (let k = 0; k < BLOCK_LEN; k++) block[k] ^= r[k];
s.push(...Array.from(encryptBlock(xk, block)));
}
let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d)));
s.fill(0);
if (decrypt) y = -y;
const m = i % 2 === 0 ? u : v;
let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m));
// STR(radix, m, c)
const C = Array(m).fill(0);
for (let i = 0; i < m; i++, c /= BigInt(radix)) C[m - 1 - i] = Number(c % BigInt(radix));
A.fill(0);
A = B;
B = C;
return [A, B];
};
const destroy = () => {
clean(xk, PQ);
};
return { u, round, destroy };
}
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
/**
* FPE-FF1 format-preserving encryption.
* @param radix - Alphabet size for each input digit.
* @param key - AES key bytes.
* @param tweak - Optional tweak bytes.
* @returns Encrypt/decrypt helpers over digit arrays.
* @example
* Encrypts decimal digits without changing their format, using a fresh AES key.
*
* ```ts
* import { FF1 } from '@noble/ciphers/ff1.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const ff1 = FF1(10, key);
* ff1.encrypt([1, 2, 3]);
* ```
*/
export function FF1(
radix: number,
key: TArg<Uint8Array>,
tweak: TArg<Uint8Array> = EMPTY_BUF
): { encrypt(x: number[]): number[]; decrypt(x: number[]): number[] } {
anumber(radix);
abytes(key);
abytes(tweak);
// This borrows caller key/tweak buffers by reference through the bound closure; mutating them
// after construction changes later encrypt/decrypt outputs.
const PQ = getRound.bind(null, radix, key, tweak);
return {
encrypt(x: number[]): number[] {
const { u, round, destroy } = PQ(x);
let [A, B] = [x.slice(0, u), x.slice(u)];
for (let i = 0; i < 10; i++) [A, B] = round(A, B, i);
destroy();
const res = A.concat(B);
A.fill(0);
B.fill(0);
return res;
},
decrypt(x: number[]): number[] {
const { u, round, destroy } = PQ(x);
// The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm;
// the differences are in Step 6, where:
// 1) the order of the indices is reversed,
// 2) the roles of A and B are swapped
// 3) modular addition is replaced by modular subtraction, in Step 6vi.
let [B, A] = [x.slice(0, u), x.slice(u)];
for (let i = 9; i >= 0; i--) [A, B] = round(A, B, i, true);
destroy();
const res = B.concat(A);
A.fill(0);
B.fill(0);
return res;
},
};
}
// Binary wrapper uses little-endian bit order within each byte so bit 0 stays
// in the first numeral slot for this library-defined byte-array surface.
const binLE = {
encode(bytes: TArg<Uint8Array>): number[] {
const x = [];
for (let i = 0; i < bytes.length; i++) {
for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) x.push(tmp & 1);
}
return x;
},
decode(b: number[]): TRet<Uint8Array> {
if (!Array.isArray(b) || b.length % 8) throw new Error('Invalid binary string');
const res = new Uint8Array(b.length / 8);
for (let i = 0, j = 0; i < res.length; i++) {
res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3);
res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7);
}
return res as TRet<Uint8Array>;
},
};
/**
* Binary FPE-FF1 wrapper over byte arrays.
* @param key - AES key bytes.
* @param tweak - Optional tweak bytes.
* @returns Encrypt/decrypt helpers over byte arrays.
* @example
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
*
* ```ts
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const ff1 = BinaryFF1(key);
* ff1.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export function BinaryFF1(
key: TArg<Uint8Array>,
tweak: TArg<Uint8Array> = EMPTY_BUF
): TRet<Cipher> {
const ff1 = FF1(2, key, tweak);
return {
encrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> =>
binLE.decode(ff1.encrypt(binLE.encode(x))) as TRet<Uint8Array>,
decrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> =>
binLE.decode(ff1.decrypt(binLE.encode(x))) as TRet<Uint8Array>,
} as TRet<Cipher>;
}
+25
View File
@@ -0,0 +1,25 @@
/**
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
* @example
```js
import { gcm, aessiv } from '@noble/ciphers/aes.js';
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
// Unauthenticated encryption: make sure to use HMAC or similar
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
// KW
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
// Utilities
import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js';
import { poly1305 } from '@noble/ciphers/_poly1305.js';
import { ghash, polyval } from '@noble/ciphers/_polyval.js';
```
* @module
*/
throw new Error('root module cannot be imported: import submodules instead. Check out README');
+374
View File
@@ -0,0 +1,374 @@
/**
* Salsa20 stream cipher, released in 2005.
* Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
* which are hard to implement in a constant-time manner.
* Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
*
* - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20},
* extended-nonce
* variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits,
* and became safe to be picked at random.
* - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
* We provide the alias and corresponding seal / open methods.
* "crypto_box" and "sealedbox" are available in package
* {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}.
* - Check out
* {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF}
* and {@link https://cr.yp.to/snuffle.html | website}.
* @module
*/
import { createCipher, rotl } from './_arx.ts';
import { poly1305 } from './_poly1305.ts';
import {
abytes,
clean,
equalBytes,
getOutput,
swap32IfBE,
swap8IfBE,
wrapCipher,
type ARXCipher,
type CipherWithOutput,
type TArg,
type TRet,
type XorStream,
} from './utils.ts';
/**
* Salsa20 core function. It is implemented twice:
* 1. Simple loop (salsaCore_small, hsalsa_small)
* 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read
* The specific implementation is selected in `createCipher` below.
* Performance numbers for 1MB inputs:
* * default x 779 ops/sec @ 1ms/op
* * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op
* * small x 132 ops/sec @ 7ms/op
*/
/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */
function salsaQR(x: TArg<Uint32Array>, a: number, b: number, c: number, d: number) {
x[b] ^= rotl((x[a] + x[d]) | 0, 7);
x[c] ^= rotl((x[b] + x[a]) | 0, 9);
x[d] ^= rotl((x[c] + x[b]) | 0, 13);
x[a] ^= rotl((x[d] + x[c]) | 0, 18);
}
/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */
function salsaRound(x: TArg<Uint32Array>, rounds = 20) {
for (let r = 0; r < rounds; r += 2) {
salsaQR(x, 0, 4, 8, 12);
salsaQR(x, 5, 9, 13, 1);
salsaQR(x, 10, 14, 2, 6);
salsaQR(x, 15, 3, 7, 11);
salsaQR(x, 0, 1, 2, 3);
salsaQR(x, 5, 6, 7, 4);
salsaQR(x, 10, 11, 8, 9);
salsaQR(x, 15, 12, 13, 14);
}
}
// Shared scratch for the unused auditability helper below; it would be
// non-reentrant under overlapping/nested calls, but current code doesn't invoke it.
const stmp = /* @__PURE__ */ new Uint32Array(16);
/** Small version of salsa without loop unrolling. Unused, provided for auditability. */
// prettier-ignore
function salsa(
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>,
isHSalsa: boolean = true, rounds: number = 20
): void {
// Create initial array using common pattern
const y = Uint32Array.from([
s[0], k[0], k[1], k[2], // "expa" Key Key Key
k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce
i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key
k[5], k[6], k[7], s[3], // Key Key Key "te k"
]);
const x = stmp;
x.set(y);
// const x = y.slice();
salsaRound(x, rounds);
// hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state.
if (isHSalsa) {
const xindexes = [0, 5, 10, 15, 6, 7, 8, 9];
for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];
} else {
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
}
}
/** Identical to `salsaCore`. Unused. */
// @ts-ignore
const salsaCore_small: typeof salsaCore = (s, k, n, out, cnt, rounds) =>
salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds);
/** Identical to `hsalsa`. Unused. */
// @ts-ignore
const hsalsa_small: typeof hsalsa = salsa;
/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */
// prettier-ignore
function salsaCore(
s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds = 20
): void {
// Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero.
// Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}.
let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key
y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce
y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key
y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k"
// Save state to temporary variables
let x00 = y00, x01 = y01, x02 = y02, x03 = y03,
x04 = y04, x05 = y05, x06 = y06, x07 = y07,
x08 = y08, x09 = y09, x10 = y10, x11 = y11,
x12 = y12, x13 = y13, x14 = y14, x15 = y15;
for (let r = 0; r < rounds; r += 2) {
x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);
x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);
x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);
x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);
x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);
x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);
x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);
x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);
x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);
x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);
x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);
x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);
x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);
x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);
x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);
x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);
}
// Write output
let oi = 0;
out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;
out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;
out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;
out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;
out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;
out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;
out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;
out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;
}
/**
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
* Identical to `hsalsa_small`.
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
* @param s - Sigma constants as 32-bit words.
* @param k - Key words.
* @param i - Nonce-prefix words.
* @param out - Output buffer for the derived subkey.
* @example
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
*
* ```ts
* const sigma = new Uint32Array(4);
* const key = new Uint32Array(8);
* const nonce = new Uint32Array(4);
* const out = new Uint32Array(8);
* hsalsa(sigma, key, nonce, out);
* ```
*/
// prettier-ignore
export function hsalsa(
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>
): void {
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]),
x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]),
x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]),
x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]);
for (let r = 0; r < 20; r += 2) {
x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);
x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);
x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);
x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);
x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);
x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);
x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);
x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);
x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);
x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);
x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);
x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);
x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);
x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);
x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);
x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);
}
let oi = 0;
// XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material.
out[oi++] = x00; out[oi++] = x05;
out[oi++] = x10; out[oi++] = x15;
out[oi++] = x06; out[oi++] = x07;
out[oi++] = x08; out[oi++] = x09;
swap32IfBE(out);
}
/**
* Salsa20 from original paper. 8-byte nonce.
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
* @param key - 16-byte or 32-byte key.
* @param nonce - 8-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
* the high word stays zero and the implementation still caps the public
* value to 32 bits.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
*
* ```ts
* import { salsa20 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(8);
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
* ```
*/
export const salsa20: TRet<XorStream> = /* @__PURE__ */ createCipher(salsaCore, {
allowShortKeys: true,
counterRight: true,
});
/**
* XSalsa20 extended-nonce salsa.
* With 24-byte nonce, it's safe to make it random (CSPRNG).
* @param key - 32-byte key.
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
* @param nonce - 24-byte nonce.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Initial block counter.
* @returns Encrypted or decrypted bytes.
* @example
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
*
* ```ts
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
* ```
*/
export const xsalsa20: TRet<XorStream> = /* @__PURE__ */ createCipher(salsaCore, {
counterRight: true,
extendNonceFn: hsalsa,
});
/**
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
* With 24-byte nonce, it's safe to make it random (CSPRNG).
* Also known as `secretbox` from libsodium / nacl.
* No AAD input is supported here. Caller-provided `output` buffers for
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
* implementation uses a 32-byte leading scratch area before returning `+16`.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
* @returns AEAD cipher instance.
* @example
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
*
* ```ts
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const cipher = xsalsa20poly1305(key, nonce);
* cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const xsalsa20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>): TRet<CipherWithOutput> => {
// This borrows caller key/nonce buffers by reference; mutating them after construction changes
// later encrypt/decrypt outputs.
return {
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
// xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption.
// Unfortunately, makes it hard to separate tag calculation & encryption itself,
// because 32 bytes is half-block of 64-byte salsa.
// Need 32 extra bytes up front for the auth-key scratch area described above.
output = getOutput(plaintext.length + 32, output, false);
// output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext.
const authKey = output.subarray(0, 32);
const ciphPlaintext = output.subarray(32);
output.set(plaintext, 32);
// authKey is produced by xoring the first 32 bytes with zeros.
clean(authKey);
// output = stream ^ output; authKey = stream ^ zeros(32)
xsalsa20(key, nonce, output, output);
const tag = poly1305(ciphPlaintext, authKey);
output.set(tag, 16);
// Clean up auth-key remnants and the temporary tag copy.
clean(output.subarray(0, 16), tag);
// Return output[16..].
return output.subarray(16) as TRet<Uint8Array>;
},
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
// tmp part passed tag ciphertext
// [0..32] [32..48] [48..]
// Authenticate the ciphertext before decrypting it; on tag failure the scratch/output
// buffer may already contain copied ciphertext and derived auth-key material.
abytes(ciphertext);
output = getOutput(ciphertext.length + 32, output, false);
// output[0..32] is auth-key scratch, output[32..48] is passed tag,
// output[48..] is ciphertext then plaintext.
const tmp = output.subarray(0, 32);
const passedTag = output.subarray(32, 48);
const ciphPlaintext = output.subarray(48);
output.set(ciphertext, 32);
// authKey is produced by xoring the scratch area with zeros.
clean(tmp);
const authKey = xsalsa20(key, nonce, tmp, tmp);
const tag = poly1305(ciphPlaintext, authKey);
if (!equalBytes(passedTag, tag)) {
clean(output);
throw new Error('invalid tag');
}
// output = stream ^ output[16..]
xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
clean(tmp, passedTag, tag);
// Return output[48..], skipping zeroized output[0..48].
return ciphPlaintext as TRet<Uint8Array>;
},
} as TRet<CipherWithOutput>;
}
);
/**
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
* for `crypto_box`.
* @param key - 32-byte key.
* @param nonce - 24-byte nonce.
* @returns Wrapper with `seal()` and `open()` helpers.
* @example
* Uses the libsodium-style `seal()` and `open()` wrapper.
*
* ```ts
* import { secretbox } from '@noble/ciphers/salsa.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(32);
* const nonce = randomBytes(24);
* const box = secretbox(key, nonce);
* box.seal(new Uint8Array([1, 2, 3]));
* ```
*/
export function secretbox(
key: TArg<Uint8Array>,
nonce: TArg<Uint8Array>
): TRet<{
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
}> {
const xs = xsalsa20poly1305(key, nonce);
return { seal: xs.encrypt, open: xs.decrypt } as TRet<{
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
}>;
}
+1191
View File
File diff suppressed because it is too large Load Diff
+226
View File
@@ -0,0 +1,226 @@
/**
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
* @module
*/
import { abytes, anumber, type AsyncCipher, type TArg, type TRet } from './utils.ts';
function getWebcryptoSubtle(): any {
const cr = typeof globalThis !== 'undefined' && (globalThis as any).crypto;
if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle;
throw new Error('crypto.subtle must be defined');
}
type WebcryptoUtils = {
encrypt(
key: TArg<Uint8Array>,
keyParams: unknown,
cryptParams: unknown,
plaintext: TArg<Uint8Array>
): Promise<TRet<Uint8Array>>;
decrypt(
key: TArg<Uint8Array>,
keyParams: unknown,
cryptParams: unknown,
ciphertext: TArg<Uint8Array>
): Promise<TRet<Uint8Array>>;
};
/**
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
* for example in React Native.
* Raw keys are re-imported on every call; this wrapper intentionally does not
* cache `CryptoKey` objects between operations.
*/
export const utils: TRet<WebcryptoUtils> = {
async encrypt(
key: TArg<Uint8Array>,
keyParams: any,
cryptParams: any,
plaintext: TArg<Uint8Array>
): Promise<TRet<Uint8Array>> {
const cr = getWebcryptoSubtle();
const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);
const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);
return new Uint8Array(ciphertext) as TRet<Uint8Array>;
},
async decrypt(
key: TArg<Uint8Array>,
keyParams: any,
cryptParams: any,
ciphertext: TArg<Uint8Array>
): Promise<TRet<Uint8Array>> {
const cr = getWebcryptoSubtle();
const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);
const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);
return new Uint8Array(plaintext) as TRet<Uint8Array>;
},
};
const mode = {
CBC: 'AES-CBC',
CTR: 'AES-CTR',
GCM: 'AES-GCM',
} as const;
type BlockMode = (typeof mode)[keyof typeof mode];
function getCryptParams(algo: BlockMode, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) {
if (algo === mode.CBC) return { name: mode.CBC, iv: nonce };
// WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap.
if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 128 };
if (algo === mode.GCM) {
// Rely on the backend default tag length (128 bits) instead of setting it explicitly.
if (AAD) return { name: mode.GCM, iv: nonce, additionalData: AAD };
else return { name: mode.GCM, iv: nonce };
}
throw new Error('unknown aes block mode');
}
function generate(
algo: BlockMode,
nonceLength: number
): TRet<
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}
> {
anumber(nonceLength);
const res = (
key: TArg<Uint8Array>,
nonce: TArg<Uint8Array>,
AAD?: TArg<Uint8Array>
): TRet<AsyncCipher> => {
abytes(key);
abytes(nonce);
// Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD".
if (AAD !== undefined) abytes(AAD, undefined, 'AAD');
// Exact nonce-length enforcement and WebCrypto-specific AAD normalization are
// delegated to the backend; locally we only require byte-array inputs here.
// Keep caller key/nonce/AAD by reference; mutating them after
// construction changes later operations.
const keyParams = { name: algo, length: key.length * 8 };
const cryptParams = getCryptParams(algo, nonce, AAD);
let consumed = false;
return {
// keyLength,
encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>> {
abytes(plaintext);
if (consumed) throw new Error('Cannot encrypt() twice with same key / nonce');
consumed = true;
return utils.encrypt(key, keyParams, cryptParams, plaintext);
},
decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>> {
abytes(ciphertext);
return utils.decrypt(key, keyParams, cryptParams, ciphertext);
},
} as TRet<AsyncCipher>;
};
res.nonceLength = nonceLength;
res.blockSize = 16; // always for AES
return res as TRet<
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}
>;
}
/**
* AES-CBC implemented with WebCrypto.
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
* delegated to the backend instead of local `abytes(..., 16)` validation.
* @param key - AES key bytes.
* @param iv - 16-byte initialization vector.
* @returns Async cipher instance.
* @example
* Encrypts a block with the browser or Node WebCrypto backend.
*
* ```ts
* import { cbc } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const iv = randomBytes(16);
* const cipher = cbc(key, iv);
* await cipher.encrypt(new Uint8Array(16));
* ```
*/
export const cbc: TRet<
((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}
> = /* @__PURE__ */ (() => generate(mode.CBC, 16))();
/**
* AES-CTR implemented with WebCrypto.
* Uses WebCrypto's full 128-bit counter-length setting so the whole
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
* @param key - AES key bytes.
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
* @returns Async cipher instance.
* @example
* Encrypts a short payload with WebCrypto AES-CTR.
*
* ```ts
* import { ctr } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(16);
* const cipher = ctr(key, nonce);
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const ctr: TRet<
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}
> = /* @__PURE__ */ (() => generate(mode.CTR, 16))();
/**
* AES-GCM implemented with WebCrypto.
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
* to the backend WebCrypto implementation.
* @param key - AES key bytes.
* @param nonce - Nonce bytes.
* @param AAD - Additional authenticated data.
* @returns Async cipher instance.
* @example
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
*
* ```ts
* import { gcm } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(12);
* const cipher = gcm(key, nonce);
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const gcm: TRet<
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}
> = /* @__PURE__ */ (() => generate(mode.GCM, 12))();
// // Type tests
// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts';
// import { xsalsa20poly1305 } from '../salsa.ts';
// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts';
// const wsiv = managedNonce(siv);
// const wgcm = managedNonce(gcm);
// const wctr = managedNonce(ctr);
// const wcbc = managedNonce(cbc);
// const wsalsapoly = managedNonce(xsalsa20poly1305);
// const wchacha = managedNonce(chacha20poly1305);
// const wxchacha = managedNonce(xchacha20poly1305);
// // should fail
// const wcbc2 = managedNonce(managedNonce(cbc));
// const wctr = managedNonce(ctr);
// import { gcm as gcmSync } from '../aes.ts';
// const x1 = managedNonce(gcmSync);
// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher
// const x2 = managedNonce(gcm);
// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher
+717
View File
@@ -0,0 +1,717 @@
/**
* Utilities for hex, bytes, CSPRNG.
* @module
*/
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
/**
* Bytes API type helpers for old + new TypeScript.
*
* TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.
* We can't use specific return type, because TS 5.6 will error.
* We can't use generic return type, because most TS 5.9 software will expect specific type.
*
* Maps typed-array input leaves to broad forms.
* These are compatibility adapters, not ownership guarantees.
*
* - `TArg` keeps byte inputs broad.
* - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.
*/
export type TypedArg<T> = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never;
/** Maps typed-array output leaves to narrow TS-compatible forms. */
export type TypedRet<T> = T extends BigInt64Array ? ReturnType<typeof BigInt64Array.of> : T extends BigUint64Array ? ReturnType<typeof BigUint64Array.of> : T extends Float32Array ? ReturnType<typeof Float32Array.of> : T extends Float64Array ? ReturnType<typeof Float64Array.of> : T extends Int16Array ? ReturnType<typeof Int16Array.of> : T extends Int32Array ? ReturnType<typeof Int32Array.of> : T extends Int8Array ? ReturnType<typeof Int8Array.of> : T extends Uint16Array ? ReturnType<typeof Uint16Array.of> : T extends Uint32Array ? ReturnType<typeof Uint32Array.of> : T extends Uint8ClampedArray ? ReturnType<typeof Uint8ClampedArray.of> : T extends Uint8Array ? ReturnType<typeof Uint8Array.of> : never;
/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */
export type TArg<T> = T | ([TypedArg<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
[K in keyof A]: TRet<A[K]>;
}) => TArg<R>) & {
[K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;
} : T extends [infer A, ...infer R] ? [TArg<A>, ...{
[K in keyof R]: TArg<R[K]>;
}] : T extends readonly [infer A, ...infer R] ? readonly [TArg<A>, ...{
[K in keyof R]: TArg<R[K]>;
}] : T extends (infer A)[] ? TArg<A>[] : T extends readonly (infer A)[] ? readonly TArg<A>[] : T extends Promise<infer A> ? Promise<TArg<A>> : T extends object ? {
[K in keyof T]: TArg<T[K]>;
} : T : TypedArg<T>);
/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */
export type TRet<T> = T extends unknown ? T & ([TypedRet<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
[K in keyof A]: TArg<A[K]>;
}) => TRet<R>) & {
[K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;
} : T extends [infer A, ...infer R] ? [TRet<A>, ...{
[K in keyof R]: TRet<R[K]>;
}] : T extends readonly [infer A, ...infer R] ? readonly [TRet<A>, ...{
[K in keyof R]: TRet<R[K]>;
}] : T extends (infer A)[] ? TRet<A>[] : T extends readonly (infer A)[] ? readonly TRet<A>[] : T extends Promise<infer A> ? Promise<TRet<A>> : T extends object ? {
[K in keyof T]: TRet<T[K]>;
} : T : TypedRet<T>) : never;
/**
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
* @param a - Value to inspect.
* @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
* @example
* Guards a value before treating it as raw key material.
*
* ```ts
* isBytes(new Uint8Array());
* ```
*/
export declare function isBytes(a: unknown): a is Uint8Array;
/**
* Asserts something is boolean.
* @param b - Value to validate.
* @throws On wrong argument types. {@link TypeError}
* @example
* Validates a boolean option before branching on it.
*
* ```ts
* abool(true);
* ```
*/
export declare function abool(b: boolean): void;
/**
* Asserts something is a non-negative safe integer.
* @param n - Value to validate.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @example
* Validates a non-negative length or counter.
*
* ```ts
* anumber(1);
* ```
*/
export declare function anumber(n: number): void;
/**
* Asserts something is Uint8Array.
* @param value - Value to validate.
* @param length - Expected byte length.
* @param title - Optional label used in error messages.
* @returns The validated byte array.
* On Node, `Buffer` is accepted too because it is a Uint8Array view.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument lengths. {@link RangeError}
* @example
* Validates a fixed-length nonce or key buffer.
*
* ```ts
* abytes(new Uint8Array([1, 2]), 2);
* ```
*/
export declare function abytes(value: TArg<Uint8Array>, length?: number, title?: string): TRet<Uint8Array>;
/**
* Asserts a hash- or MAC-like instance has not been destroyed or finished.
* @param instance - Stateful instance to validate.
* @param checkFinished - Whether to reject finished instances.
* When `false`, only `destroyed` is checked.
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
* @example
* Guards against calling `update()` or `digest()` on a finished hash.
*
* ```ts
* aexists({ destroyed: false, finished: false });
* ```
*/
export declare function aexists(instance: any, checkFinished?: boolean): void;
/**
* Asserts output is a properly-sized byte array.
* @param out - Output buffer to validate.
* @param instance - Hash-like instance providing `outputLen`.
* This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
* unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
* @throws On wrong argument types. {@link TypeError}
* @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
* @throws On wrong output buffer lengths. {@link RangeError}
* @throws On wrong output buffer alignment. {@link Error}
* @example
* Verifies that a caller-provided output buffer is large enough.
*
* ```ts
* aoutput(new Uint8Array(16), { outputLen: 16 });
* ```
*/
export declare function aoutput(out: any, instance: any, onlyAligned?: boolean): void;
/** One-shot hash helper with `.create()`. */
export type IHash = {
(data: string | TArg<Uint8Array>): TRet<Uint8Array>;
/** Input block size in bytes. */
blockLen: number;
/** Digest size in bytes. */
outputLen: number;
/** Creates a fresh incremental hash instance of the same algorithm. */
create: any;
};
/** One-shot MAC helper with `.create()`. */
export type CMac<H extends IHash2 = IHash2, A extends any[] = []> = {
(msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array>;
/** Input block size in bytes. */
blockLen: number;
/** Digest size in bytes. */
outputLen: number;
/**
* Creates a fresh incremental MAC instance of the same algorithm.
* @param key - MAC key bytes.
* @param args - Additional constructor arguments, when the MAC wrapper needs them.
* @returns Fresh incremental MAC instance.
*/
create(key: TArg<Uint8Array>, ...args: A): H;
};
/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
/**
* Casts a typed-array view to Uint8Array.
* @param arr - Typed-array view to reinterpret.
* @returns Uint8Array view over the same bytes.
* @example
* Views 32-bit words as raw bytes without copying.
*
* ```ts
* u8(new Uint32Array([1]));
* ```
*/
export declare function u8(arr: TArg<TypedArray>): TRet<Uint8Array>;
/**
* Casts a typed-array view to Uint32Array.
* @param arr - Typed-array view to reinterpret.
* @returns Uint32Array view over the same bytes. Callers are expected to provide a
* 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
* @example
* Views a byte buffer as 32-bit words for block processing.
*
* ```ts
* u32(new Uint8Array(4));
* ```
*/
export declare function u32(arr: TArg<TypedArray>): TRet<Uint32Array>;
/**
* Zeroizes typed arrays in place.
* Warning: JS provides no guarantees.
* @param arrays - Arrays to wipe.
* @example
* Wipes a temporary key buffer after use.
*
* ```ts
* const bytes = new Uint8Array([1]);
* clean(bytes);
* ```
*/
export declare function clean(...arrays: TArg<TypedArray[]>): void;
/**
* Creates a DataView for byte-level manipulation.
* @param arr - Typed-array view to wrap.
* @returns DataView over the same bytes.
* @example
* Creates an endian-aware view for length encoding.
*
* ```ts
* createView(new Uint8Array(4));
* ```
*/
export declare function createView(arr: TArg<TypedArray>): DataView;
/**
* Whether the current platform is little-endian.
* Most are; some IBM systems are not.
*/
export declare const isLE: boolean;
/**
* Reverses byte order of one 32-bit word.
* @param word - Unsigned 32-bit word to swap.
* @returns The same word with bytes reversed.
* @example
* Swaps a big-endian word into little-endian byte order.
*
* ```ts
* byteSwap(0x11223344);
* ```
*/
export declare const byteSwap: (word: number) => number;
/**
* Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
* @param n - Unsigned 32-bit word to normalize.
* @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
* @example
* Normalizes a host-endian word before passing it into an ARX/AES core.
*
* ```ts
* swap8IfBE(0x11223344);
* ```
*/
export declare const swap8IfBE: (n: number) => number;
/**
* Byte-swaps every word of a Uint32Array in place.
* @param arr - Uint32Array whose words should be swapped.
* @returns The same array after in-place byte swapping.
* @example
* Swaps every 32-bit word in a word-view buffer.
*
* ```ts
* byteSwap32(new Uint32Array([0x11223344]));
* ```
*/
export declare const byteSwap32: (arr: TArg<Uint32Array>) => TRet<Uint32Array>;
/**
* Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
* @param u - Word view to normalize in place.
* @returns Little-endian normalized word view.
* @example
* Normalizes a word-view buffer before block processing.
*
* ```ts
* swap32IfBE(new Uint32Array([0x11223344]));
* ```
*/
export declare const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array>;
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @param bytes - Bytes to encode.
* @returns Lowercase hexadecimal string.
* @throws On wrong argument types. {@link TypeError}
* @example
* Formats ciphertext bytes for logs or test vectors.
*
* ```ts
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
* ```
*/
export declare function bytesToHex(bytes: TArg<Uint8Array>): string;
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @param hex - Hexadecimal string to decode.
* @returns Decoded bytes.
* @throws On wrong argument types. {@link TypeError}
* @throws On malformed hexadecimal input. {@link RangeError}
* @example
* Parses a hex test vector into bytes.
*
* ```ts
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
* ```
*/
export declare function hexToBytes(hex: string): TRet<Uint8Array>;
/**
* Converts a big-endian hex string into bigint.
* @param hex - Hexadecimal string without `0x`.
* @returns Parsed bigint value. The empty string is treated as `0n`.
* @throws On wrong argument types. {@link TypeError}
* @example
* Parses a big-endian field element or counter from hex.
*
* ```ts
* hexToNumber('ff');
* ```
*/
export declare function hexToNumber(hex: string): bigint;
/**
* Converts big-endian bytes into bigint.
* @param bytes - Big-endian bytes.
* @returns Parsed bigint value. Empty input is treated as `0n`.
* @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
* @example
* Reads a big-endian integer from serialized bytes.
*
* ```ts
* bytesToNumberBE(new Uint8Array([1, 0]));
* ```
*/
export declare function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint;
/**
* Converts a number into big-endian bytes of fixed length.
* @param n - Number to encode.
* @param len - Output length in bytes.
* @returns Big-endian bytes padded to `len`.
* Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
* and values that do not fit surface through the downstream hex parser instead of a
* dedicated range guard here.
* @throws On wrong argument types. {@link TypeError}
* @throws If the requested output length cannot represent the encoded value. {@link RangeError}
* @example
* Encodes a counter as fixed-width big-endian bytes.
*
* ```ts
* numberToBytesBE(1, 2);
* ```
*/
export declare function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array>;
/**
* Converts string to bytes using UTF8 encoding.
* @param str - String to encode.
* @returns UTF-8 bytes in a detached fresh Uint8Array copy.
* @throws On wrong argument types. {@link TypeError}
* @example
* Encodes application text before encryption or MACing.
*
* ```ts
* utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
* ```
*/
export declare function utf8ToBytes(str: string): TRet<Uint8Array>;
/**
* Converts bytes to string using UTF8 encoding.
* @param bytes - UTF-8 bytes.
* @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
* UTF-8 is replacement-decoded instead of rejected.
* @example
* Decodes UTF-8 plaintext back into a string.
*
* ```ts
* bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
* ```
*/
export declare function bytesToUtf8(bytes: TArg<Uint8Array>): string;
/**
* Checks if two U8A use same underlying buffer and overlaps.
* This is invalid and can corrupt data.
* @param a - First byte view.
* @param b - Second byte view.
* @returns `true` when the views overlap in memory.
* @example
* Detects whether two slices alias the same backing buffer.
*
* ```ts
* overlapBytes(new Uint8Array(4), new Uint8Array(4));
* ```
*/
export declare function overlapBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
/**
* If input and output overlap and input starts before output, we will overwrite end of input before
* we start processing it, so this is not supported for most ciphers
* (except chacha/salsa, which were designed for this)
* @param input - Input bytes.
* @param output - Output bytes.
* @throws If the output view would overwrite unread input bytes. {@link Error}
* @example
* Rejects an in-place layout that would overwrite unread input bytes.
*
* ```ts
* complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
* ```
*/
export declare function complexOverlapBytes(input: TArg<Uint8Array>, output: TArg<Uint8Array>): void;
/**
* Copies several Uint8Arrays into one.
* @param arrays - Byte arrays to concatenate.
* @returns Combined byte array.
* @throws On wrong argument types inside the byte-array list. {@link TypeError}
* @example
* Builds a `nonce || ciphertext` style buffer.
*
* ```ts
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
* ```
*/
export declare function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array>;
type EmptyObj = {};
/**
* Merges user options into defaults.
* @param defaults - Default option values.
* @param opts - User-provided overrides.
* @returns Combined options object.
* The merge mutates `defaults` in place and returns the same object.
* @throws If options are missing or not an object. {@link Error}
* @example
* Applies user overrides to the default cipher options.
*
* ```ts
* checkOpts({ rounds: 20 }, { rounds: 8 });
* ```
*/
export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts: T2): T1 & T2;
/**
* Compares two byte arrays in kinda constant time once lengths already match.
* @param a - First byte array.
* @param b - Second byte array.
* @returns `true` when the arrays contain the same bytes. Different lengths still return early.
* @example
* Compares an expected authentication tag with the received one.
*
* ```ts
* equalBytes(new Uint8Array([1]), new Uint8Array([1]));
* ```
*/
export declare function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
/** Incremental hash interface used internally. */
export interface IHash2 {
/** Bytes processed per compression block. */
blockLen: number;
/** Bytes produced by the final digest. */
outputLen: number;
/**
* Absorbs one more chunk into the hash state.
* @param buf - Data chunk to hash.
* @returns The same hash instance for chaining.
*/
update(buf: string | TArg<Uint8Array>): this;
/**
* Writes the final digest into a caller-provided buffer.
* @param buf - Destination buffer for the digest bytes.
* @returns Nothing. Implementations write into `buf` in place.
*/
digestInto(buf: TArg<Uint8Array>): void;
/**
* Finalizes the hash and returns a fresh digest buffer.
* @returns Digest bytes.
*/
digest(): TRet<Uint8Array>;
/**
* Resets internal state. Makes Hash instance unusable.
* Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed
* by user, they will need to manually call `destroy()` when zeroing is necessary.
*/
destroy(): void;
}
/**
* Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
* @param keyLen - Valid probe-key length used to read static metadata once.
* The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
* can pass any representative size as long as those values stay fixed.
* @param macCons - Keyed MAC constructor or factory.
* @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
* @returns Callable MAC helper with `.create()`.
*/
export declare function wrapMacConstructor<H extends IHash2, A extends any[] = []>(keyLen: number, macCons: TArg<(key: Uint8Array, ...args: A) => H>, fromMsg?: TArg<(msg: Uint8Array) => A>): TRet<CMac<H, A>>;
/** Sync cipher: takes byte array and returns byte array. */
export type Cipher = {
/**
* Encrypts plaintext bytes.
* @param plaintext - Data to encrypt.
* @returns Ciphertext bytes.
*/
encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array>;
/**
* Decrypts ciphertext bytes.
* @param ciphertext - Data to decrypt.
* @returns Plaintext bytes.
*/
decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array>;
};
/** Async cipher e.g. from built-in WebCrypto. */
export type AsyncCipher = {
/**
* Encrypts plaintext bytes.
* @param plaintext - Data to encrypt.
* @returns Promise resolving to ciphertext bytes.
*/
encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
/**
* Decrypts ciphertext bytes.
* @param ciphertext - Data to decrypt.
* @returns Promise resolving to plaintext bytes.
*/
decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
};
/** Cipher with `output` argument which can optimize by doing 1 less allocation. */
export type CipherWithOutput = Cipher & {
/**
* Encrypts plaintext bytes into an optional caller-provided buffer.
* @param plaintext - Data to encrypt.
* @param output - Optional destination buffer.
* @returns Ciphertext bytes.
*/
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
/**
* Decrypts ciphertext bytes into an optional caller-provided buffer.
* @param ciphertext - Data to decrypt.
* @param output - Optional destination buffer.
* @returns Plaintext bytes.
*/
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
};
/**
* Params are outside of return type, so it is accessible before calling constructor.
* If function support multiple nonceLength's, we return the best one.
*/
export type CipherParams = {
/** Cipher block size in bytes. */
blockSize: number;
/** Nonce length in bytes when the cipher uses a fixed nonce size. */
nonceLength?: number;
/** Authentication-tag length in bytes for AEAD modes. */
tagLength?: number;
/** Whether nonce length is variable at runtime. */
varSizeNonce?: boolean;
};
/**
* ARX AEAD cipher, like salsa or chacha.
* @param key - Secret key bytes.
* @param nonce - Nonce bytes.
* @param AAD - Optional associated data.
* @returns Cipher instance with caller-managed output buffers.
*/
export type ARXCipher = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => CipherWithOutput) & {
blockSize: number;
nonceLength: number;
tagLength: number;
};
/**
* Cipher constructor signature.
* @param key - Secret key bytes.
* @param args - Additional constructor arguments, such as nonce or IV.
* @returns Cipher instance.
*/
export type CipherCons<T extends any[]> = (key: TArg<Uint8Array>, ...args: T) => Cipher;
/**
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
* Used internally by the exported cipher constructors.
* Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
* arity (`fn.length === 2`), and tag-bearing constructors are expected to use
* `args[1]` for optional AAD.
* @__NO_SIDE_EFFECTS__
* @param params - Static cipher metadata. See {@link CipherParams}.
* @param constructor - Cipher constructor.
* @returns Wrapped constructor with validation.
*/
export declare const wrapCipher: <C extends CipherCons<any>, P extends CipherParams>(params: P, constructor: C) => C & P;
/**
* Represents a Salsa or ChaCha xor stream.
* @param key - Secret key bytes.
* @param nonce - Nonce bytes.
* @param data - Input bytes to xor with the keystream.
* @param output - Optional destination buffer.
* @param counter - Optional starting block counter.
* @returns Output bytes.
*/
export type XorStream = (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, data: TArg<Uint8Array>, output?: TArg<Uint8Array>, counter?: number) => TRet<Uint8Array>;
/**
* By default, returns u8a of length.
* When out is available, it checks it for validity and uses it.
* @param expectedLength - Required output length.
* @param out - Optional destination buffer.
* @param onlyAligned - Whether `out` must be 4-byte aligned.
* @returns Output buffer ready for writing.
* @throws On wrong argument types. {@link TypeError}
* @throws If the provided output buffer has the wrong size or alignment. {@link Error}
* @example
* Reuses a caller-provided output buffer when lengths match.
*
* ```ts
* getOutput(16, new Uint8Array(16));
* ```
*/
export declare function getOutput(expectedLength: number, out?: TArg<Uint8Array>, onlyAligned?: boolean): TRet<Uint8Array>;
/**
* Encodes data and AAD bit lengths into a 16-byte buffer.
* @param dataLength - Data length in bits.
* @param aadLength - AAD length in bits.
* The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
* conventions even though the helper parameter order is `(dataLength, aadLength)`.
* @param isLE - Whether to encode lengths as little-endian.
* @returns 16-byte length block.
* @throws On wrong argument types passed to the endian validator. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @example
* Builds the length block appended by GCM and Poly1305.
*
* ```ts
* u64Lengths(16, 8, true);
* ```
*/
export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet<Uint8Array>;
/**
* Checks whether a byte array is aligned to a 4-byte offset.
* @param bytes - Byte array to inspect.
* @returns `true` when the view is 4-byte aligned.
* @example
* Checks whether a buffer can be safely viewed as Uint32Array.
*
* ```ts
* isAligned32(new Uint8Array(4));
* ```
*/
export declare function isAligned32(bytes: TArg<Uint8Array>): boolean;
/**
* Copies bytes into a new Uint8Array.
* @param bytes - Bytes to copy.
* @returns Copied byte array.
* @throws On wrong argument types. {@link TypeError}
* @example
* Copies input into an aligned Uint8Array before block processing.
*
* ```ts
* copyBytes(new Uint8Array([1, 2]));
* ```
*/
export declare function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array>;
/**
* Cryptographically secure PRNG.
* Uses internal OS-level `crypto.getRandomValues`.
* @param bytesLength - Number of bytes to produce.
* Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
* non-integers, negative lengths, and oversize requests surface backend/runtime errors.
* @returns Random byte array.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
* @example
* Generates a fresh nonce or key.
*
* ```ts
* randomBytes(16);
* ```
*/
export declare function randomBytes(bytesLength?: number): TRet<Uint8Array>;
/**
* The pseudorandom number generator doesn't wipe current state:
* instead, it generates new one based on previous state + entropy.
* Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes,
* which is in fact `reseed`, since it changes counter too.
*/
export interface PRG {
/**
* Mixes fresh entropy into the current generator state.
* @param seed - Entropy bytes to absorb.
*/
addEntropy(seed: TArg<Uint8Array>): void;
/**
* Produces a requested number of pseudorandom bytes.
* @param bytesLength - Number of bytes to generate.
* @returns Random byte array.
*/
randomBytes(bytesLength: number): TRet<Uint8Array>;
/** Destroys the generator state. */
clean(): void;
}
/** Removes the nonce argument from a cipher constructor type. */
export type RemoveNonce<T extends (...args: any) => any> = T extends (arg0: any, arg1: any, ...rest: infer R) => infer Ret ? (key: TArg<Uint8Array>, ...args: R) => Ret : never;
/**
* Cipher constructor that requires a nonce argument.
* @param key - Secret key bytes.
* @param nonce - Nonce bytes.
* @param args - Additional cipher-specific arguments.
* @returns Cipher instance.
*/
export type CipherWithNonce = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, ...args: any[]) => Cipher | AsyncCipher) & {
nonceLength: number;
};
/**
* Uses CSPRNG for nonce, nonce injected in ciphertext.
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
* are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
* buffer on encrypt and intentionally does not support caller-provided destination buffers.
* Too-short decrypt inputs are split into short/empty nonce views and then delegated
* to the wrapped cipher instead of being rejected here first.
*
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
* should be limited to `2**23` (8M) messages to get a collision chance of
* `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
* `2**-33`, still negligible but creeping up.
* @param fn - Cipher constructor that expects a nonce.
* @param randomBytes_ - Random-byte source used for nonce generation.
* @returns Cipher constructor that prepends the nonce to ciphertext.
* @throws On wrong argument types. {@link TypeError}
* @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
* @example
* Prepends a fresh random nonce to every ciphertext.
*
* ```ts
* import { gcm } from '@noble/ciphers/aes.js';
* import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';
* const wrapped = managedNonce(gcm);
* const key = randomBytes(16);
* const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
* wrapped(key).decrypt(ciphertext);
* ```
*/
export declare function managedNonce<T extends CipherWithNonce>(fn: T, randomBytes_?: typeof randomBytes): TRet<RemoveNonce<T>>;
/** `Uint8Array.of()` return type helper for TS 5.9. */
export type Uint8ArrayBuffer = TRet<Uint8Array>;
export {};
//# sourceMappingURL=utils.d.ts.map
+1
View File
File diff suppressed because one or more lines are too long
+807
View File
@@ -0,0 +1,807 @@
/**
* Utilities for hex, bytes, CSPRNG.
* @module
*/
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
/**
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
* @param a - Value to inspect.
* @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
* @example
* Guards a value before treating it as raw key material.
*
* ```ts
* isBytes(new Uint8Array());
* ```
*/
export function isBytes(a) {
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /
// cross-realm cases. The fallback still requires a real ArrayBuffer view
// so plain JSON-deserialized `{ constructor: ... }`
// spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
return (a instanceof Uint8Array ||
(ArrayBuffer.isView(a) &&
a.constructor.name === 'Uint8Array' &&
'BYTES_PER_ELEMENT' in a &&
a.BYTES_PER_ELEMENT === 1));
}
/**
* Asserts something is boolean.
* @param b - Value to validate.
* @throws On wrong argument types. {@link TypeError}
* @example
* Validates a boolean option before branching on it.
*
* ```ts
* abool(true);
* ```
*/
export function abool(b) {
if (typeof b !== 'boolean')
throw new TypeError(`boolean expected, not ${b}`);
}
/**
* Asserts something is a non-negative safe integer.
* @param n - Value to validate.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @example
* Validates a non-negative length or counter.
*
* ```ts
* anumber(1);
* ```
*/
export function anumber(n) {
if (typeof n !== 'number')
throw new TypeError('number expected, got ' + typeof n);
if (!Number.isSafeInteger(n) || n < 0)
throw new RangeError('positive integer expected, got ' + n);
}
/**
* Asserts something is Uint8Array.
* @param value - Value to validate.
* @param length - Expected byte length.
* @param title - Optional label used in error messages.
* @returns The validated byte array.
* On Node, `Buffer` is accepted too because it is a Uint8Array view.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument lengths. {@link RangeError}
* @example
* Validates a fixed-length nonce or key buffer.
*
* ```ts
* abytes(new Uint8Array([1, 2]), 2);
* ```
*/
export function abytes(value, length, title = '') {
const bytes = isBytes(value);
const len = value?.length;
const needsLen = length !== undefined;
if (!bytes || (needsLen && len !== length)) {
const prefix = title && `"${title}" `;
const ofLen = needsLen ? ` of length ${length}` : '';
const got = bytes ? `length=${len}` : `type=${typeof value}`;
const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
if (!bytes)
throw new TypeError(message);
throw new RangeError(message);
}
return value;
}
/**
* Asserts a hash- or MAC-like instance has not been destroyed or finished.
* @param instance - Stateful instance to validate.
* @param checkFinished - Whether to reject finished instances.
* When `false`, only `destroyed` is checked.
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
* @example
* Guards against calling `update()` or `digest()` on a finished hash.
*
* ```ts
* aexists({ destroyed: false, finished: false });
* ```
*/
export function aexists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error('Hash instance has been destroyed');
if (checkFinished && instance.finished)
throw new Error('Hash#digest() has already been called');
}
/**
* Asserts output is a properly-sized byte array.
* @param out - Output buffer to validate.
* @param instance - Hash-like instance providing `outputLen`.
* This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
* unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
* @throws On wrong argument types. {@link TypeError}
* @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
* @throws On wrong output buffer lengths. {@link RangeError}
* @throws On wrong output buffer alignment. {@link Error}
* @example
* Verifies that a caller-provided output buffer is large enough.
*
* ```ts
* aoutput(new Uint8Array(16), { outputLen: 16 });
* ```
*/
export function aoutput(out, instance, onlyAligned = false) {
abytes(out, undefined, 'output');
const min = instance.outputLen;
if (out.length < min) {
throw new RangeError('digestInto() expects output buffer of length at least ' + min);
}
if (onlyAligned && !isAligned32(out))
throw new Error('invalid output, must be aligned');
}
/**
* Casts a typed-array view to Uint8Array.
* @param arr - Typed-array view to reinterpret.
* @returns Uint8Array view over the same bytes.
* @example
* Views 32-bit words as raw bytes without copying.
*
* ```ts
* u8(new Uint32Array([1]));
* ```
*/
export function u8(arr) {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/**
* Casts a typed-array view to Uint32Array.
* @param arr - Typed-array view to reinterpret.
* @returns Uint32Array view over the same bytes. Callers are expected to provide a
* 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
* @example
* Views a byte buffer as 32-bit words for block processing.
*
* ```ts
* u32(new Uint8Array(4));
* ```
*/
export function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/**
* Zeroizes typed arrays in place.
* Warning: JS provides no guarantees.
* @param arrays - Arrays to wipe.
* @example
* Wipes a temporary key buffer after use.
*
* ```ts
* const bytes = new Uint8Array([1]);
* clean(bytes);
* ```
*/
export function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
/**
* Creates a DataView for byte-level manipulation.
* @param arr - Typed-array view to wrap.
* @returns DataView over the same bytes.
* @example
* Creates an endian-aware view for length encoding.
*
* ```ts
* createView(new Uint8Array(4));
* ```
*/
export function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/**
* Whether the current platform is little-endian.
* Most are; some IBM systems are not.
*/
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/**
* Reverses byte order of one 32-bit word.
* @param word - Unsigned 32-bit word to swap.
* @returns The same word with bytes reversed.
* @example
* Swaps a big-endian word into little-endian byte order.
*
* ```ts
* byteSwap(0x11223344);
* ```
*/
export const byteSwap = (word) => ((word << 24) & 0xff000000) |
((word << 8) & 0xff0000) |
((word >>> 8) & 0xff00) |
((word >>> 24) & 0xff);
/**
* Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
* @param n - Unsigned 32-bit word to normalize.
* @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
* @example
* Normalizes a host-endian word before passing it into an ARX/AES core.
*
* ```ts
* swap8IfBE(0x11223344);
* ```
*/
export const swap8IfBE = isLE
? (n) => n
: (n) => byteSwap(n) >>> 0;
/**
* Byte-swaps every word of a Uint32Array in place.
* @param arr - Uint32Array whose words should be swapped.
* @returns The same array after in-place byte swapping.
* @example
* Swaps every 32-bit word in a word-view buffer.
*
* ```ts
* byteSwap32(new Uint32Array([0x11223344]));
* ```
*/
export const byteSwap32 = (arr) => {
for (let i = 0; i < arr.length; i++)
arr[i] = byteSwap(arr[i]);
return arr;
};
/**
* Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
* @param u - Word view to normalize in place.
* @returns Little-endian normalized word view.
* @example
* Normalizes a word-view buffer before block processing.
*
* ```ts
* swap32IfBE(new Uint32Array([0x11223344]));
* ```
*/
export const swap32IfBE = isLE
? (u) => u
: byteSwap32;
// Built-in hex conversion:
// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}
const hasHexBuiltin = /* @__PURE__ */ (() =>
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @param bytes - Bytes to encode.
* @returns Lowercase hexadecimal string.
* @throws On wrong argument types. {@link TypeError}
* @example
* Formats ciphertext bytes for logs or test vectors.
*
* ```ts
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
* ```
*/
export function bytesToHex(bytes) {
abytes(bytes);
// @ts-ignore
if (hasHexBuiltin)
return bytes.toHex();
// pre-caching improves the speed 6x
let hex = '';
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
if (ch >= asciis._0 && ch <= asciis._9)
return ch - asciis._0; // '2' => 50-48
if (ch >= asciis.A && ch <= asciis.F)
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
if (ch >= asciis.a && ch <= asciis.f)
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
return;
}
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @param hex - Hexadecimal string to decode.
* @returns Decoded bytes.
* @throws On wrong argument types. {@link TypeError}
* @throws On malformed hexadecimal input. {@link RangeError}
* @example
* Parses a hex test vector into bytes.
*
* ```ts
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
* ```
*/
export function hexToBytes(hex) {
if (typeof hex !== 'string')
throw new TypeError('hex string expected, got ' + typeof hex);
if (hasHexBuiltin) {
try {
return Uint8Array.fromHex(hex);
}
catch (error) {
if (error instanceof SyntaxError)
throw new RangeError(error.message);
throw error;
}
}
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === undefined || n2 === undefined) {
const char = hex[hi] + hex[hi + 1];
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
}
return array;
}
// Used in micro
/**
* Converts a big-endian hex string into bigint.
* @param hex - Hexadecimal string without `0x`.
* @returns Parsed bigint value. The empty string is treated as `0n`.
* @throws On wrong argument types. {@link TypeError}
* @example
* Parses a big-endian field element or counter from hex.
*
* ```ts
* hexToNumber('ff');
* ```
*/
export function hexToNumber(hex) {
if (typeof hex !== 'string')
throw new TypeError('hex string expected, got ' + typeof hex);
return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian
}
// Used in ff1
// BE: Big Endian, LE: Little Endian
/**
* Converts big-endian bytes into bigint.
* @param bytes - Big-endian bytes.
* @returns Parsed bigint value. Empty input is treated as `0n`.
* @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
* @example
* Reads a big-endian integer from serialized bytes.
*
* ```ts
* bytesToNumberBE(new Uint8Array([1, 0]));
* ```
*/
export function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
// Used in micro, ff1
/**
* Converts a number into big-endian bytes of fixed length.
* @param n - Number to encode.
* @param len - Output length in bytes.
* @returns Big-endian bytes padded to `len`.
* Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
* and values that do not fit surface through the downstream hex parser instead of a
* dedicated range guard here.
* @throws On wrong argument types. {@link TypeError}
* @throws If the requested output length cannot represent the encoded value. {@link RangeError}
* @example
* Encodes a counter as fixed-width big-endian bytes.
*
* ```ts
* numberToBytesBE(1, 2);
* ```
*/
export function numberToBytesBE(n, len) {
// Reject coercible non-numeric inputs before string/hex conversion changes behavior.
if (typeof n === 'number')
anumber(n);
else if (typeof n !== 'bigint')
throw new TypeError(`number or bigint expected, got ${typeof n}`);
anumber(len);
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
}
/**
* Converts string to bytes using UTF8 encoding.
* @param str - String to encode.
* @returns UTF-8 bytes in a detached fresh Uint8Array copy.
* @throws On wrong argument types. {@link TypeError}
* @example
* Encodes application text before encryption or MACing.
*
* ```ts
* utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
* ```
*/
export function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new TypeError('string expected');
return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}
}
/**
* Converts bytes to string using UTF8 encoding.
* @param bytes - UTF-8 bytes.
* @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
* UTF-8 is replacement-decoded instead of rejected.
* @example
* Decodes UTF-8 plaintext back into a string.
*
* ```ts
* bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
* ```
*/
export function bytesToUtf8(bytes) {
return new TextDecoder().decode(bytes);
}
/**
* Checks if two U8A use same underlying buffer and overlaps.
* This is invalid and can corrupt data.
* @param a - First byte view.
* @param b - Second byte view.
* @returns `true` when the views overlap in memory.
* @example
* Detects whether two slices alias the same backing buffer.
*
* ```ts
* overlapBytes(new Uint8Array(4), new Uint8Array(4));
* ```
*/
export function overlapBytes(a, b) {
// Zero-length views cannot overwrite anything, even if their offset sits inside another range.
if (!a.byteLength || !b.byteLength)
return false;
return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
);
}
/**
* If input and output overlap and input starts before output, we will overwrite end of input before
* we start processing it, so this is not supported for most ciphers
* (except chacha/salsa, which were designed for this)
* @param input - Input bytes.
* @param output - Output bytes.
* @throws If the output view would overwrite unread input bytes. {@link Error}
* @example
* Rejects an in-place layout that would overwrite unread input bytes.
*
* ```ts
* complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
* ```
*/
export function complexOverlapBytes(input, output) {
// This is very cursed. It works somehow, but I'm completely unsure,
// reasoning about overlapping aligned windows is very hard.
if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
throw new Error('complex overlap of input and output is not supported');
}
/**
* Copies several Uint8Arrays into one.
* @param arrays - Byte arrays to concatenate.
* @returns Combined byte array.
* @throws On wrong argument types inside the byte-array list. {@link TypeError}
* @example
* Builds a `nonce || ciphertext` style buffer.
*
* ```ts
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
* ```
*/
export function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
/**
* Merges user options into defaults.
* @param defaults - Default option values.
* @param opts - User-provided overrides.
* @returns Combined options object.
* The merge mutates `defaults` in place and returns the same object.
* @throws If options are missing or not an object. {@link Error}
* @example
* Applies user overrides to the default cipher options.
*
* ```ts
* checkOpts({ rounds: 20 }, { rounds: 8 });
* ```
*/
export function checkOpts(defaults, opts) {
if (opts == null || typeof opts !== 'object')
throw new Error('options must be defined');
const merged = Object.assign(defaults, opts);
return merged;
}
/**
* Compares two byte arrays in kinda constant time once lengths already match.
* @param a - First byte array.
* @param b - Second byte array.
* @returns `true` when the arrays contain the same bytes. Different lengths still return early.
* @example
* Compares an expected authentication tag with the received one.
*
* ```ts
* equalBytes(new Uint8Array([1]), new Uint8Array([1]));
* ```
*/
export function equalBytes(a, b) {
if (a.length !== b.length)
return false;
let diff = 0;
for (let i = 0; i < a.length; i++)
diff |= a[i] ^ b[i];
return diff === 0;
}
/**
* Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
* @param keyLen - Valid probe-key length used to read static metadata once.
* The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
* can pass any representative size as long as those values stay fixed.
* @param macCons - Keyed MAC constructor or factory.
* @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
* @returns Callable MAC helper with `.create()`.
*/
export function wrapMacConstructor(keyLen, macCons, fromMsg) {
const mac = macCons;
const getArgs = (fromMsg || (() => []));
const macC = (msg, key) => mac(key, ...getArgs(msg))
.update(msg)
.digest();
const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
macC.outputLen = tmp.outputLen;
macC.blockLen = tmp.blockLen;
macC.create = (key, ...args) => mac(key, ...args);
return macC;
}
/**
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
* Used internally by the exported cipher constructors.
* Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
* arity (`fn.length === 2`), and tag-bearing constructors are expected to use
* `args[1]` for optional AAD.
* @__NO_SIDE_EFFECTS__
* @param params - Static cipher metadata. See {@link CipherParams}.
* @param constructor - Cipher constructor.
* @returns Wrapped constructor with validation.
*/
export const wrapCipher = (params, constructor) => {
function wrappedCipher(key, ...args) {
// Validate key
abytes(key, undefined, 'key');
// Validate nonce if nonceLength is present
if (params.nonceLength !== undefined) {
const nonce = args[0];
abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');
}
// Validate AAD if tagLength present
const tagl = params.tagLength;
if (tagl && args[1] !== undefined)
abytes(args[1], undefined, 'AAD');
const cipher = constructor(key, ...args);
const checkOutput = (fnLength, output) => {
if (output !== undefined) {
if (fnLength !== 2)
throw new Error('cipher output not supported');
abytes(output, undefined, 'output');
}
};
// Create wrapped cipher with validation and single-use encryption
let called = false;
const wrCipher = {
encrypt(data, output) {
if (called)
throw new Error('cannot encrypt() twice with same key + nonce');
called = true;
abytes(data);
checkOutput(cipher.encrypt.length, output);
return cipher.encrypt(data, output);
},
decrypt(data, output) {
abytes(data);
if (tagl && data.length < tagl)
throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
checkOutput(cipher.decrypt.length, output);
return cipher.decrypt(data, output);
},
};
return wrCipher;
}
Object.assign(wrappedCipher, params);
return wrappedCipher;
};
/**
* By default, returns u8a of length.
* When out is available, it checks it for validity and uses it.
* @param expectedLength - Required output length.
* @param out - Optional destination buffer.
* @param onlyAligned - Whether `out` must be 4-byte aligned.
* @returns Output buffer ready for writing.
* @throws On wrong argument types. {@link TypeError}
* @throws If the provided output buffer has the wrong size or alignment. {@link Error}
* @example
* Reuses a caller-provided output buffer when lengths match.
*
* ```ts
* getOutput(16, new Uint8Array(16));
* ```
*/
export function getOutput(expectedLength, out, onlyAligned = true) {
if (out === undefined)
return new Uint8Array(expectedLength);
// Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.
abytes(out, undefined, 'output');
if (out.length !== expectedLength)
throw new Error('"output" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length);
if (onlyAligned && !isAligned32(out))
throw new Error('invalid output, must be aligned');
return out;
}
/**
* Encodes data and AAD bit lengths into a 16-byte buffer.
* @param dataLength - Data length in bits.
* @param aadLength - AAD length in bits.
* The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
* conventions even though the helper parameter order is `(dataLength, aadLength)`.
* @param isLE - Whether to encode lengths as little-endian.
* @returns 16-byte length block.
* @throws On wrong argument types passed to the endian validator. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @example
* Builds the length block appended by GCM and Poly1305.
*
* ```ts
* u64Lengths(16, 8, true);
* ```
*/
export function u64Lengths(dataLength, aadLength, isLE) {
// Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.
anumber(dataLength);
anumber(aadLength);
abool(isLE);
const num = new Uint8Array(16);
const view = createView(num);
view.setBigUint64(0, BigInt(aadLength), isLE);
view.setBigUint64(8, BigInt(dataLength), isLE);
return num;
}
/**
* Checks whether a byte array is aligned to a 4-byte offset.
* @param bytes - Byte array to inspect.
* @returns `true` when the view is 4-byte aligned.
* @example
* Checks whether a buffer can be safely viewed as Uint32Array.
*
* ```ts
* isAligned32(new Uint8Array(4));
* ```
*/
export function isAligned32(bytes) {
return bytes.byteOffset % 4 === 0;
}
/**
* Copies bytes into a new Uint8Array.
* @param bytes - Bytes to copy.
* @returns Copied byte array.
* @throws On wrong argument types. {@link TypeError}
* @example
* Copies input into an aligned Uint8Array before block processing.
*
* ```ts
* copyBytes(new Uint8Array([1, 2]));
* ```
*/
export function copyBytes(bytes) {
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
// because callers use it at byte-validation boundaries before mutating the detached copy.
return Uint8Array.from(abytes(bytes));
}
/**
* Cryptographically secure PRNG.
* Uses internal OS-level `crypto.getRandomValues`.
* @param bytesLength - Number of bytes to produce.
* Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
* non-integers, negative lengths, and oversize requests surface backend/runtime errors.
* @returns Random byte array.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
* @example
* Generates a fresh nonce or key.
*
* ```ts
* randomBytes(16);
* ```
*/
export function randomBytes(bytesLength = 32) {
// Validate upfront so fractional / coercible lengths do not silently
// truncate through Uint8Array().
anumber(bytesLength);
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
if (typeof cr?.getRandomValues !== 'function')
throw new Error('crypto.getRandomValues must be defined');
return cr.getRandomValues(new Uint8Array(bytesLength));
}
/**
* Uses CSPRNG for nonce, nonce injected in ciphertext.
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
* are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
* buffer on encrypt and intentionally does not support caller-provided destination buffers.
* Too-short decrypt inputs are split into short/empty nonce views and then delegated
* to the wrapped cipher instead of being rejected here first.
*
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
* should be limited to `2**23` (8M) messages to get a collision chance of
* `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
* `2**-33`, still negligible but creeping up.
* @param fn - Cipher constructor that expects a nonce.
* @param randomBytes_ - Random-byte source used for nonce generation.
* @returns Cipher constructor that prepends the nonce to ciphertext.
* @throws On wrong argument types. {@link TypeError}
* @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
* @example
* Prepends a fresh random nonce to every ciphertext.
*
* ```ts
* import { gcm } from '@noble/ciphers/aes.js';
* import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';
* const wrapped = managedNonce(gcm);
* const key = randomBytes(16);
* const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
* wrapped(key).decrypt(ciphertext);
* ```
*/
export function managedNonce(fn, randomBytes_ = randomBytes) {
const { nonceLength } = fn;
anumber(nonceLength);
const addNonce = (nonce, ciphertext, plaintext) => {
const out = concatBytes(nonce, ciphertext);
// Wrapped ciphers may alias caller plaintext on encrypt(); never zero
// caller-owned buffers here.
if (!overlapBytes(plaintext, ciphertext))
ciphertext.fill(0);
return out;
};
// NOTE: we cannot support DST here, it would be mistake:
// - we don't know how much dst length cipher requires
// - nonce may unalign dst and break everything
// - we create new u8a anyway (concatBytes)
// - previously we passed all args to cipher, but that was mistake!
const res = ((key, ...args) => ({
encrypt(plaintext) {
abytes(plaintext);
const nonce = randomBytes_(nonceLength);
const encrypted = fn(key, nonce, ...args).encrypt(plaintext);
// @ts-ignore
if (encrypted instanceof Promise)
return encrypted.then((ct) => addNonce(nonce, ct, plaintext));
return addNonce(nonce, encrypted, plaintext);
},
decrypt(ciphertext) {
abytes(ciphertext);
const nonce = ciphertext.subarray(0, nonceLength);
const decrypted = ciphertext.subarray(nonceLength);
return fn(key, nonce, ...args).decrypt(decrypted);
},
}));
// Auto-nonce wrappers still preserve the wrapped payload geometry.
if ('blockSize' in fn)
res.blockSize = fn.blockSize;
if ('tagLength' in fn)
res.tagLength = fn.tagLength;
return res;
}
//# sourceMappingURL=utils.js.map
+1
View File
File diff suppressed because one or more lines are too long
+89
View File
@@ -0,0 +1,89 @@
/**
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
* @module
*/
import { type AsyncCipher, type TArg, type TRet } from './utils.ts';
type WebcryptoUtils = {
encrypt(key: TArg<Uint8Array>, keyParams: unknown, cryptParams: unknown, plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
decrypt(key: TArg<Uint8Array>, keyParams: unknown, cryptParams: unknown, ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
};
/**
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
* for example in React Native.
* Raw keys are re-imported on every call; this wrapper intentionally does not
* cache `CryptoKey` objects between operations.
*/
export declare const utils: TRet<WebcryptoUtils>;
/**
* AES-CBC implemented with WebCrypto.
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
* delegated to the backend instead of local `abytes(..., 16)` validation.
* @param key - AES key bytes.
* @param iv - 16-byte initialization vector.
* @returns Async cipher instance.
* @example
* Encrypts a block with the browser or Node WebCrypto backend.
*
* ```ts
* import { cbc } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const iv = randomBytes(16);
* const cipher = cbc(key, iv);
* await cipher.encrypt(new Uint8Array(16));
* ```
*/
export declare const cbc: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}>;
/**
* AES-CTR implemented with WebCrypto.
* Uses WebCrypto's full 128-bit counter-length setting so the whole
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
* @param key - AES key bytes.
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
* @returns Async cipher instance.
* @example
* Encrypts a short payload with WebCrypto AES-CTR.
*
* ```ts
* import { ctr } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(16);
* const cipher = ctr(key, nonce);
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const ctr: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}>;
/**
* AES-GCM implemented with WebCrypto.
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
* to the backend WebCrypto implementation.
* @param key - AES key bytes.
* @param nonce - Nonce bytes.
* @param AAD - Additional authenticated data.
* @returns Async cipher instance.
* @example
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
*
* ```ts
* import { gcm } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(12);
* const cipher = gcm(key, nonce);
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export declare const gcm: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
blockSize: number;
nonceLength: number;
}>;
export {};
//# sourceMappingURL=webcrypto.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmB,KAAK,WAAW,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAQrF,KAAK,cAAc,GAAG;IACpB,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,GAC1B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAC7B,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;CAC9B,CAAC;AACF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,cAAc,CAuBtC,CAAC;AAwEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAClE,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC1F,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC"}
+167
View File
@@ -0,0 +1,167 @@
/**
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
* @module
*/
import { abytes, anumber } from "./utils.js";
function getWebcryptoSubtle() {
const cr = typeof globalThis !== 'undefined' && globalThis.crypto;
if (cr && typeof cr.subtle === 'object' && cr.subtle != null)
return cr.subtle;
throw new Error('crypto.subtle must be defined');
}
/**
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
* for example in React Native.
* Raw keys are re-imported on every call; this wrapper intentionally does not
* cache `CryptoKey` objects between operations.
*/
export const utils = {
async encrypt(key, keyParams, cryptParams, plaintext) {
const cr = getWebcryptoSubtle();
const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);
const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);
return new Uint8Array(ciphertext);
},
async decrypt(key, keyParams, cryptParams, ciphertext) {
const cr = getWebcryptoSubtle();
const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);
const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);
return new Uint8Array(plaintext);
},
};
const mode = {
CBC: 'AES-CBC',
CTR: 'AES-CTR',
GCM: 'AES-GCM',
};
function getCryptParams(algo, nonce, AAD) {
if (algo === mode.CBC)
return { name: mode.CBC, iv: nonce };
// WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap.
if (algo === mode.CTR)
return { name: mode.CTR, counter: nonce, length: 128 };
if (algo === mode.GCM) {
// Rely on the backend default tag length (128 bits) instead of setting it explicitly.
if (AAD)
return { name: mode.GCM, iv: nonce, additionalData: AAD };
else
return { name: mode.GCM, iv: nonce };
}
throw new Error('unknown aes block mode');
}
function generate(algo, nonceLength) {
anumber(nonceLength);
const res = (key, nonce, AAD) => {
abytes(key);
abytes(nonce);
// Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD".
if (AAD !== undefined)
abytes(AAD, undefined, 'AAD');
// Exact nonce-length enforcement and WebCrypto-specific AAD normalization are
// delegated to the backend; locally we only require byte-array inputs here.
// Keep caller key/nonce/AAD by reference; mutating them after
// construction changes later operations.
const keyParams = { name: algo, length: key.length * 8 };
const cryptParams = getCryptParams(algo, nonce, AAD);
let consumed = false;
return {
// keyLength,
encrypt(plaintext) {
abytes(plaintext);
if (consumed)
throw new Error('Cannot encrypt() twice with same key / nonce');
consumed = true;
return utils.encrypt(key, keyParams, cryptParams, plaintext);
},
decrypt(ciphertext) {
abytes(ciphertext);
return utils.decrypt(key, keyParams, cryptParams, ciphertext);
},
};
};
res.nonceLength = nonceLength;
res.blockSize = 16; // always for AES
return res;
}
/**
* AES-CBC implemented with WebCrypto.
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
* delegated to the backend instead of local `abytes(..., 16)` validation.
* @param key - AES key bytes.
* @param iv - 16-byte initialization vector.
* @returns Async cipher instance.
* @example
* Encrypts a block with the browser or Node WebCrypto backend.
*
* ```ts
* import { cbc } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const iv = randomBytes(16);
* const cipher = cbc(key, iv);
* await cipher.encrypt(new Uint8Array(16));
* ```
*/
export const cbc = /* @__PURE__ */ (() => generate(mode.CBC, 16))();
/**
* AES-CTR implemented with WebCrypto.
* Uses WebCrypto's full 128-bit counter-length setting so the whole
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
* @param key - AES key bytes.
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
* @returns Async cipher instance.
* @example
* Encrypts a short payload with WebCrypto AES-CTR.
*
* ```ts
* import { ctr } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(16);
* const cipher = ctr(key, nonce);
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const ctr = /* @__PURE__ */ (() => generate(mode.CTR, 16))();
/**
* AES-GCM implemented with WebCrypto.
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
* to the backend WebCrypto implementation.
* @param key - AES key bytes.
* @param nonce - Nonce bytes.
* @param AAD - Additional authenticated data.
* @returns Async cipher instance.
* @example
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
*
* ```ts
* import { gcm } from '@noble/ciphers/webcrypto.js';
* import { randomBytes } from '@noble/ciphers/utils.js';
* const key = randomBytes(16);
* const nonce = randomBytes(12);
* const cipher = gcm(key, nonce);
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
* ```
*/
export const gcm = /* @__PURE__ */ (() => generate(mode.GCM, 12))();
// // Type tests
// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts';
// import { xsalsa20poly1305 } from '../salsa.ts';
// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts';
// const wsiv = managedNonce(siv);
// const wgcm = managedNonce(gcm);
// const wctr = managedNonce(ctr);
// const wcbc = managedNonce(cbc);
// const wsalsapoly = managedNonce(xsalsa20poly1305);
// const wchacha = managedNonce(chacha20poly1305);
// const wxchacha = managedNonce(xchacha20poly1305);
// // should fail
// const wcbc2 = managedNonce(managedNonce(cbc));
// const wctr = managedNonce(ctr);
// import { gcm as gcmSync } from '../aes.ts';
// const x1 = managedNonce(gcmSync);
// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher
// const x2 = managedNonce(gcm);
// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher
//# sourceMappingURL=webcrypto.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,OAAO,EAA0C,MAAM,YAAY,CAAC;AAErF,SAAS,kBAAkB;IACzB,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,WAAW,IAAK,UAAkB,CAAC,MAAM,CAAC;IAC3E,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC;IAC/E,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC;AAgBD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAyB;IACzC,KAAK,CAAC,OAAO,CACX,GAAqB,EACrB,SAAc,EACd,WAAgB,EAChB,SAA2B;QAE3B,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;QAChC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;QAC1E,MAAM,UAAU,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QAClE,OAAO,IAAI,UAAU,CAAC,UAAU,CAAqB,CAAC;IACxD,CAAC;IACD,KAAK,CAAC,OAAO,CACX,GAAqB,EACrB,SAAc,EACd,WAAgB,EAChB,UAA4B;QAE5B,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;QAChC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC;QAClE,OAAO,IAAI,UAAU,CAAC,SAAS,CAAqB,CAAC;IACvD,CAAC;CACF,CAAC;AAEF,MAAM,IAAI,GAAG;IACX,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;CACN,CAAC;AAGX,SAAS,cAAc,CAAC,IAAe,EAAE,KAAuB,EAAE,GAAsB;IACtF,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC5D,gGAAgG;IAChG,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;IAC9E,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC;QACtB,sFAAsF;QACtF,IAAI,GAAG;YAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,EAAE,CAAC;;YAC9D,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC5C,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,QAAQ,CACf,IAAe,EACf,WAAmB;IAOnB,OAAO,CAAC,WAAW,CAAC,CAAC;IACrB,MAAM,GAAG,GAAG,CACV,GAAqB,EACrB,KAAuB,EACvB,GAAsB,EACH,EAAE;QACrB,MAAM,CAAC,GAAG,CAAC,CAAC;QACZ,MAAM,CAAC,KAAK,CAAC,CAAC;QACd,yFAAyF;QACzF,IAAI,GAAG,KAAK,SAAS;YAAE,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QACrD,8EAA8E;QAC9E,4EAA4E;QAC5E,8DAA8D;QAC9D,yCAAyC;QACzC,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzD,MAAM,WAAW,GAAG,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;QACrD,IAAI,QAAQ,GAAG,KAAK,CAAC;QACrB,OAAO;YACL,aAAa;YACb,OAAO,CAAC,SAA2B;gBACjC,MAAM,CAAC,SAAS,CAAC,CAAC;gBAClB,IAAI,QAAQ;oBAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBAC9E,QAAQ,GAAG,IAAI,CAAC;gBAChB,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;YAC/D,CAAC;YACD,OAAO,CAAC,UAA4B;gBAClC,MAAM,CAAC,UAAU,CAAC,CAAC;gBACnB,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;YAChE,CAAC;SACmB,CAAC;IACzB,CAAC,CAAC;IACF,GAAG,CAAC,WAAW,GAAG,WAAW,CAAC;IAC9B,GAAG,CAAC,SAAS,GAAG,EAAE,CAAC,CAAC,iBAAiB;IACrC,OAAO,GAKN,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AACrD;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AACrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AAErD,gBAAgB;AAChB,uDAAuD;AACvD,kDAAkD;AAClD,sEAAsE;AAEtE,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,qDAAqD;AACrD,kDAAkD;AAClD,oDAAoD;AAEpD,iBAAiB;AACjB,iDAAiD;AACjD,kCAAkC;AAClC,8CAA8C;AAC9C,oCAAoC;AACpC,yEAAyE;AACzE,gCAAgC;AAChC,8EAA8E"}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+563
View File
@@ -0,0 +1,563 @@
# noble-hashes
Audited & minimal JS implementation of hash functions, MACs and KDFs.
- 🔒 [**Audited**](#security) by an independent security firm
- 🔻 Tree-shakeable: unused code is excluded from your builds
- 🏎 Fast: hand-optimized for caveats of JS engines
- 🔍 Reliable: chained / sliding window / DoS / ACVP tests and fuzzing
- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x
- 🦘 Includes SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF, Scrypt, Argon2
- 🥈 Optional, friendly wrapper over native WebCrypto
- 🪶 22KB (gzipped) for everything, 2.4KB for single-hash build
Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative.
Check out [Upgrading](#upgrading) for information about upgrading from previous versions.
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-hashes/discussions) for questions and support.
The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/).
### This library belongs to _noble_ cryptography
> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
- Zero or minimal dependencies
- Highly readable TypeScript / JS code
- PGP-signed releases and transparent NPM builds
- All libraries:
[ciphers](https://github.com/paulmillr/noble-ciphers),
[curves](https://github.com/paulmillr/noble-curves),
[hashes](https://github.com/paulmillr/noble-hashes),
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
[ed25519](https://github.com/paulmillr/noble-ed25519)
- [Check out the homepage](https://paulmillr.com/noble/)
for reading resources, documentation, and apps built with noble
## Usage
> `npm install @noble/hashes`
> `deno add jsr:@noble/hashes`
We support all major platforms and runtimes.
For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).
A standalone file [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available.
```js
// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size
import { sha256 as noble_sha256 } from '@noble/hashes/sha2.js';
const hash = noble_sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23]));
// Available modules
import { sha256, sha384, sha512, sha224, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
import {
sha3_256, sha3_512,
keccak_256, keccak_512,
shake128, shake256,
} from '@noble/hashes/sha3.js';
import {
cshake256, turboshake256, kmac256, tuplehash256,
kt128, kt256, keccakprg,
} from '@noble/hashes/sha3-addons.js';
import { blake3 } from '@noble/hashes/blake3.js';
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
import { blake256, blake512 } from '@noble/hashes/blake1.js';
import { sha1, md5, ripemd160 } from '@noble/hashes/legacy.js';
import { hmac } from '@noble/hashes/hmac.js';
import { hkdf } from '@noble/hashes/hkdf.js';
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
import * as webcrypto from '@noble/hashes/webcrypto.js';
// const { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } = webcrypto;
import * as utils from '@noble/hashes/utils.js';
const { bytesToHex, concatBytes, equalBytes, hexToBytes } = utils;
```
- [sha2: sha256, sha384, sha512](#sha2-sha256-sha384-sha512-and-others)
- [sha3: FIPS, SHAKE, Keccak](#sha3-fips-shake-keccak)
- [sha3-addons: cSHAKE, KMAC, KT128, TurboSHAKE](#sha3-addons-cshake-kmac-kt128-turboshake)
- [blake1, blake2, blake3](#blake1-blake2-blake3)
- [legacy: sha1, md5, ripemd160](#legacy-sha1-md5-ripemd160)
- MACs: [hmac](#hmac) | [kmac](#sha3-addons-cshake-kmac-kt128-turboshake) | [blake3 key mode](#blake1-blake2-blake3)
- KDFs: [hkdf](#hkdf) | [pbkdf2](#pbkdf2) | [scrypt](#scrypt) | [argon2](#argon2)
- [webcrypto: friendly wrapper](#webcrypto-friendly-wrapper)
- [utils](#utils)
- [Security](#security) | [Speed](#speed) | [Contributing & testing](#contributing--testing) | [License](#license)
### Implementations
Hash functions:
- `sha256()`: receive & return `Uint8Array`
- `sha256.create().update(a).update(b).digest()`: support partial updates
- `blake3.create({ context: 'e', dkLen: 32 })`: can have options
- support little-endian architecture; also experimentally big-endian
- can hash up to 4GB per chunk, with any amount of chunks
#### sha2: sha256, sha384, sha512 and others
```typescript
import { sha224, sha256, sha384, sha512, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
const res = sha256(Uint8Array.from([0xbc])); // basic
for (let hash of [sha256, sha384, sha512, sha224, sha512_224, sha512_256]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
```
Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
[the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
#### sha3: FIPS, SHAKE, Keccak
```typescript
import {
sha3_224, sha3_256, sha3_384, sha3_512,
keccak_224, keccak_256, keccak_384, keccak_512,
shake128, shake256,
} from '@noble/hashes/sha3.js';
for (let hash of [
sha3_224, sha3_256, sha3_384, sha3_512,
keccak_224, keccak_256, keccak_384, keccak_512,
]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
const shka = shake128(Uint8Array.from([0x10]), { dkLen: 512 });
const shkb = shake256(Uint8Array.from([0x30]), { dkLen: 512 });
```
Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
[Website](https://keccak.team/keccak.html).
Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub)
#### sha3-addons: cSHAKE, KMAC, K12, TurboSHAKE
```typescript
import {
cshake128, cshake256, kt128, kt256,
keccakprg, kmac128, kmac256,
parallelhash256, tuplehash256,
turboshake128, turboshake256,
} from '@noble/hashes/sha3-addons.js';
const data = Uint8Array.from([0x10, 0x20, 0x30]);
const personalization = new TextEncoder().encode('def');
const ec1 = cshake128(data, { personalization });
const ec2 = cshake256(data, { personalization });
const et1 = turboshake128(data);
const et2 = turboshake256(data, { D: 0x05 });
// tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash([data])
const et3 = tuplehash256([new TextEncoder().encode('ab'), new TextEncoder().encode('c')]);
// Not parallel in JS (similar to blake3 / kt128), added for compat
const ep1 = parallelhash256(data, { blockLen: 8 });
const kk = Uint8Array.from([0xca]);
const ek10 = kmac128(kk, data);
const ek11 = kmac256(kk, data);
const ek12 = kt128(data); // kangarootwelve 128-bit
const ek13 = kt256(data); // kangarootwelve 256-bit
// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength.
// * with a capacity of 254 bits.
const p = keccakprg(254);
p.addEntropy(Uint8Array.from([1, 2, 3]));
const rand1b = p.randomBytes(32);
```
- cSHAKE, KMAC, TupleHash, ParallelHash + XOF are available, matching
[NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf)
- Reduced-round Keccak KT128 (KangarooTwelve 🦘, K12) and TurboSHAKE are available, matching
[RFC 9861](https://datatracker.ietf.org/doc/rfc9861/).
- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): pseudo-random generator based on Keccak
#### blake1, blake2, blake3
```typescript
import { blake224, blake256, blake384, blake512 } from '@noble/hashes/blake1.js';
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
import { blake3 } from '@noble/hashes/blake3.js';
for (let hash of [blake224, blake256, blake384, blake512, blake2b, blake2s, blake3]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
// blake2 advanced usage
const ab = Uint8Array.from([0x01]);
const txt = new TextEncoder();
blake2s(ab);
blake2s(ab, { key: new Uint8Array(32) });
blake2s(ab, { personalization: txt.encode('pers1234') });
blake2s(ab, { salt: txt.encode('salt1234') });
blake2b(ab);
blake2b(ab, { key: new Uint8Array(64) });
blake2b(ab, { personalization: txt.encode('pers1234pers1234') });
blake2b(ab, { salt: txt.encode('salt1234salt1234') });
// blake3 advanced usage
blake3(ab);
blake3(ab, { dkLen: 256 });
blake3(ab, { key: new Uint8Array(32) });
blake3(ab, { context: txt.encode('application-name') });
```
- Blake1 is legacy hash, one of SHA3 proposals. It is rarely used anywhere. See [pdf](https://www.aumasson.jp/blake/blake.pdf).
- Blake2 is popular fast hash. blake2b focuses on 64-bit platforms while blake2s is for 8-bit to 32-bit ones. See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net)
- Blake3 is faster, reduced-round blake2. See [Website & specs](https://blake3.io)
#### legacy: sha1, md5, ripemd160
SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:
- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
```typescript
import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js';
for (let hash of [md5, ripemd160, sha1]) {
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
const a = hash(arr);
const b = hash.create().update(arr).digest();
}
```
#### hmac
```typescript
import { hmac } from '@noble/hashes/hmac.js';
import { sha256 } from '@noble/hashes/sha2.js';
const key = new Uint8Array(32).fill(1);
const msg = new Uint8Array(32).fill(2);
const mac1 = hmac(sha256, key, msg);
const mac2 = hmac.create(sha256, key).update(msg).digest();
```
Conforms to [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104).
#### hkdf
```typescript
import { hkdf } from '@noble/hashes/hkdf.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { sha256 } from '@noble/hashes/sha2.js';
const inputKey = randomBytes(32);
const salt = randomBytes(32);
const info = new TextEncoder().encode('application-key');
const hk1 = hkdf(sha256, inputKey, salt, info, 32);
// == same as
import { extract, expand } from '@noble/hashes/hkdf.js';
const prk = extract(sha256, inputKey, salt);
const hk2 = expand(sha256, prk, info, 32);
```
Conforms to [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869).
#### pbkdf2
```typescript
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
import { sha256 } from '@noble/hashes/sha2.js';
const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
c: 524288,
dkLen: 32,
});
```
Conforms to [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898).
#### scrypt
```typescript
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
N: 2 ** 17,
r: 8,
p: 1,
dkLen: 32,
onProgress(percentage) {
console.log('progress', percentage);
},
maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p)
});
```
Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914),
[Website](https://www.tarsnap.com/scrypt.html)
- `N, r, p` are work factors. It is common to only adjust N, while keeping `r: 8, p: 1`.
See [the blog post](https://blog.filippo.io/the-scrypt-parameters/).
JS doesn't support parallelization, making increasing `p` meaningless.
- `dkLen` is the length of output bytes e.g. `32` or `64`
- `onProgress` can be used with async version of the function to report progress to a user.
- `maxmem` prevents DoS and is limited to `1GB + 1KB` (`2**30 + 2**10`), but can be adjusted using formula: `N * r * p * 128 + (128 * r * p)`
Time it takes to derive Scrypt key under different values of N (2\*\*N) on Apple M4 (mobile phones can be 1x-4x slower):
| N pow | Time | RAM |
| ----- | ---- | ----- |
| 16 | 0.1s | 64MB |
| 17 | 0.2s | 128MB |
| 18 | 0.4s | 256MB |
| 19 | 0.8s | 512MB |
| 20 | 1.5s | 1GB |
| 21 | 3.1s | 2GB |
| 22 | 6.2s | 4GB |
| 23 | 13s | 8GB |
| 24 | 27s | 16GB |
> [!NOTE]
> We support N larger than `2**20` where available, however,
> not all JS engines support >= 2GB ArrayBuffer-s.
> When using such N, you'll need to manually adjust `maxmem`, using formula above.
> Other JS implementations don't support large N-s.
#### argon2
```ts
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
const arg1 = argon2id('password', 'saltsalt', { t: 2, m: 65536, p: 1, maxmem: 2 ** 32 - 1 });
```
Argon2 [RFC 9106](https://datatracker.ietf.org/doc/html/rfc9106) implementation.
> [!WARNING]
> Argon2 can't be fast in JS, because there is no fast Uint64Array.
> It is suggested to use [Scrypt](#scrypt) instead.
> Being 5x slower than native code means brute-forcing attackers have bigger advantage.
#### webcrypto: friendly wrapper
```js
import { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } from '@noble/hashes/webcrypto.js';
import { randomBytes } from '@noble/hashes/utils.js';
const whash = await sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23]));
const key = new Uint8Array(32).fill(1);
const msg = new Uint8Array(32).fill(2);
const wmac = await hmac(sha256, key, msg);
const inputKey = randomBytes(32);
const salt = randomBytes(32);
const info = new TextEncoder().encode('application-key');
const hk1 = await hkdf(sha256, inputKey, salt, info, 32);
const pbkey1 = await pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
```
Sometimes people want to use built-in `crypto.subtle` instead of pure JS implementation.
However, it has terrible API.
We simplify access to built-ins with API which mirrors noble-hashes.
The overhead is minimal - just 30+ lines of code, which verify input correctness.
> [!NOTE]
> Webcrypto methods are always async.
#### utils
```typescript
import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils.js';
console.log(toHex(randomBytes(32)));
```
- `bytesToHex` will convert `Uint8Array` to a hex string
- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes`
## Security
The library has been audited:
- at version 2.2.0, in Apr 2026, by ourselves (self-audited)
- Scope: everything
- [Changes since audit](https://github.com/paulmillr/noble-hashes/compare/2.2.0..main)
- at version 1.0.0, in Jan 2022, independently, by [Cure53](https://cure53.de)
- PDFs: [website](https://cure53.de/pentest-report_hashing-libs.pdf), [in-repo](./audit/2022-01-05-cure53-audit-nbl2.pdf)
- Scope: everything, besides `blake3`, `sha3-addons`, `sha1` and `argon2`, which have not been audited
- The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io)
It is tested against property-based, cross-library and Wycheproof vectors,
and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing).
If you see anything unusual: investigate and report.
### Constant-timeness
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance
in a scripting language. Which means _any other JS library can't have
constant-timeness_. Even statically typed Rust, a language without GC,
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.
Use low-level libraries & languages.
### Memory dumping
The library shares state buffers between hash
function calls. The buffers are zeroed-out after each call. However, if an attacker
can read application memory, you are doomed in any case:
- At some point, input will be a string and strings are immutable in JS:
there is no way to overwrite them with zeros. For example: deriving
key from `scrypt(password, salt)` where password and salt are strings
- Input from a file will stay in file buffers
- Input / output will be re-used multiple times in application which means it could stay in memory
- `await anything()` will always write all internal variables (including numbers)
to memory. With async functions / Promises there are no guarantees when the code
chunk would be executed. Which means attacker can have plenty of time to read data from memory
- There is no way to guarantee anything about zeroing sensitive data without
complex tests-suite which will dump process memory and verify that there is
no sensitive data left. For JS it means testing all browsers (incl. mobile),
which is complex. And of course it will be useless without using the same
test-suite in the actual application that consumes the library
### Supply chain security
- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures
- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity.
- **Rare releasing** is practiced to minimize the need for re-audits by end-users.
- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk.
- We use as few dependencies as possible.
- Version ranges are locked, and changes are checked with npm-diff.
- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps.
For this package, there are 0 dependencies; and a few dev dependencies:
- jsbt contains helpers for building, benchmarking & testing secure JS apps. It is developed by the same author
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation
### Randomness
We rely on the built-in
[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues),
which is considered a cryptographically secure PRNG.
Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy.
### Quantum computers
Cryptographically relevant quantum computer, if built, will allow to
utilize Grover's algorithm to break hashes in 2^n/2 operations, instead of 2^n.
This means SHA256 should be replaced with SHA512, SHA3-256 with SHA3-512, SHAKE128 with SHAKE256 etc.
Australian ASD prohibits SHA256 and similar hashes [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
## Upgrading
Supported node.js versions:
- v2: v20.19+ (ESM-only)
- v1: v14.21+ (ESM & CJS)
v2.0 changelog:
- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+
- `.js` extension must be used for all modules
- Old: `@noble/hashes/sha3`
- New: `@noble/hashes/sha3.js`
- This simplifies working in browsers natively without transpilers
- Only allow Uint8Array as hash inputs, prohibit `string`
- Strict validation checks improve security
- To replicate previous behavior, use `utils.utf8ToBytes`
- Rename / remove some modules for consistency. Previously, sha384 resided in sha512, which was weird
- `sha256`, `sha512` => `sha2.js` (consistent with `sha3.js`)
- `blake2b`, `blake2s` => `blake2.js` (consistent with `blake3.js`, `blake1.js`)
- `ripemd160`, `sha1`, `md5` => `legacy.js` (all low-security hashes are there)
- `_assert` => `utils.js`
- `crypto` internal module got removed: use built-in WebCrypto instead
- Improve typescript types & option autocomplete
- Bump compilation target from es2020 to es2022
## Contributing & testing
`test/misc` directory contains implementations of loop unrolling and md5.
- `npm install && npm run build && npm test` will build the code and run tests.
- `npm run lint` / `npm run format` will run linter / fix linter issues.
- `npm run bench` will run benchmarks
- `npm run build:release` will build single file
- There is **additional** 20-min DoS test `npm run test:dos` and 2-hour multicore test `npm run test:slow`.
See [our approach to testing](./test/README.md)
Some hashes are outside of scope of the library:
- [Pedersen in micro-zk-proofs](https://github.com/paulmillr/micro-zk-proofs/blob/1ed5ce1253583b2e540eef7f3477fb52bf5344ff/src/pedersen.ts)
- [Poseidon in noble-curves](https://github.com/paulmillr/noble-curves/blob/3d124dd3ecec8b6634cc0b2ba1c183aded5304f9/src/abstract/poseidon.ts)
- [Poly1305 & GHash in noble-ciphers](https://github.com/paulmillr/noble-ciphers)
See [paulmillr.com/noble](https://paulmillr.com/noble/) for useful resources, articles, documentation and demos related to the library.
## Speed
```sh
npm run bench
```
Benchmarks measured on Apple M4. If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble).
```
# 32B
sha256 x 2,016,129 ops/sec @ 496ns/op
sha512 x 740,740 ops/sec @ 1μs/op
sha3_256 x 287,686 ops/sec @ 3μs/op
sha3_512 x 288,267 ops/sec @ 3μs/op
k12 x 476,190 ops/sec @ 2μs/op
blake2b x 410,340 ops/sec @ 2μs/op
blake2s x 942,507 ops/sec @ 1μs/op
blake3 x 1,006,036 ops/sec @ 994ns/op
ripemd160 x 1,410,437 ops/sec @ 709ns/op
md5 x 1,663,893 ops/sec @ 601ns/op
sha1 x 1,589,825 ops/sec @ 629ns/op
# 1MB
sha256 x 331 ops/sec @ 3ms/op
sha512 x 128 ops/sec @ 7ms/op
sha3_256 x 39 ops/sec @ 25ms/op
sha3_512 x 21 ops/sec @ 46ms/op
kt128 x 91 ops/sec @ 10ms/op
kt256 x 75 ops/sec @ 13ms/op
turboshake128 x 93 ops/sec @ 10ms/op
blake256 x 57 ops/sec @ 17ms/op
blake2b x 61 ops/sec @ 16ms/op
blake2s x 78 ops/sec @ 12ms/op
blake3 x 95 ops/sec @ 10ms/op
ripemd160 x 177 ops/sec @ 5ms/op
md5 x 250 ops/sec @ 3ms/op
sha1 x 416 ops/sec @ 2ms/op
# MAC
hmac(sha256) x 599,880 ops/sec @ 1μs/op
hmac(sha512) x 197,122 ops/sec @ 5μs/op
kmac256 x 87,981 ops/sec @ 11μs/op
blake3(key) x 796,812 ops/sec @ 1μs/op
# KDF
hkdf(sha256) x 259,942 ops/sec @ 3μs/op
blake3(context) x 424,808 ops/sec @ 2μs/op
pbkdf2(sha256, c: 2 ** 18) x 5 ops/sec @ 197ms/op
pbkdf2(sha512, c: 2 ** 18) x 1 ops/sec @ 630ms/op
scrypt(n: 2 ** 18, r: 8, p: 1) x 2 ops/sec @ 400ms/op
argon2id(t: 1, m: 256MB) 2881ms
```
The library could be 3x faster by utilizing loop unrolling. It isn't used because
unrolling a) would increase bundle size b) make lib un-readable c) current perf is "fast enough"
for most use-cases.
## License
The MIT License (MIT)
Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
See LICENSE file.
+21
View File
@@ -0,0 +1,21 @@
/**
* Internal helpers for blake hash.
* @module
*/
import { type TRet } from './utils.ts';
/**
* Internal blake permutation table.
* Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also
* reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows
* `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants.
*/
export declare const BSIGMA: TRet<Uint8Array>;
export type Num4 = {
a: number;
b: number;
c: number;
d: number;
};
export declare function G1s(a: number, b: number, c: number, d: number, x: number): Num4;
export declare function G2s(a: number, b: number, c: number, d: number, x: number): Num4;
//# sourceMappingURL=_blake.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_blake.d.ts","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAQ,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAE7C;;;;;GAKG;AAEH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,UAAU,CAkBlC,CAAC;AAGH,MAAM,MAAM,IAAI,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;CAAE,CAAC;AAKnE,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E;AAKD,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E"}
+52
View File
@@ -0,0 +1,52 @@
/**
* Internal helpers for blake hash.
* @module
*/
import { rotr } from "./utils.js";
/**
* Internal blake permutation table.
* Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also
* reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows
* `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants.
*/
// prettier-ignore
export const BSIGMA = /* @__PURE__ */ Uint8Array.from([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
// Blake1, unused in others
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
]);
// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair.
// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed
// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path.
export function G1s(a, b, c, d, x) {
a = (a + b + x) | 0;
d = rotr(d ^ a, 16);
c = (c + d) | 0;
b = rotr(b ^ c, 12);
return { a, b, c, d };
}
// 32-bit / BLAKE2s second half of G.
// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed
// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path.
export function G2s(a, b, c, d, x) {
a = (a + b + x) | 0;
d = rotr(d ^ a, 8);
c = (c + d) | 0;
b = rotr(b ^ c, 7);
return { a, b, c, d };
}
//# sourceMappingURL=_blake.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_blake.js","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAa,MAAM,YAAY,CAAC;AAE7C;;;;;GAKG;AACH,kBAAkB;AAClB,MAAM,CAAC,MAAM,MAAM,GAAqB,eAAe,CAAC,UAAU,CAAC,IAAI,CAAC;IACtE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,2BAA2B;IAC3B,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;CACrD,CAAC,CAAC;AAKH,6EAA6E;AAC7E,+EAA+E;AAC/E,mEAAmE;AACnE,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACvE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC;AAED,qCAAqC;AACrC,sFAAsF;AACtF,qEAAqE;AACrE,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACvE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC"}
+99
View File
@@ -0,0 +1,99 @@
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
import { type Hash, type TArg, type TRet } from './utils.ts';
/**
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
* Returns bits from `b` when `a` is set, otherwise from `c`.
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
* set the same bit.
* @param a - selector word
* @param b - word chosen when selector bit is set
* @param c - word chosen when selector bit is clear
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit choice primitive.
* ```ts
* Chi(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export declare function Chi(a: number, b: number, c: number): number;
/**
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
* Returns bits shared by at least two inputs.
* @param a - first input word
* @param b - second input word
* @param c - third input word
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit majority primitive.
* ```ts
* Maj(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export declare function Maj(a: number, b: number, c: number): number;
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
* strings with partial-byte tails.
* @param blockLen - internal block size in bytes
* @param outputLen - digest size in bytes
* @param padOffset - trailing length field size in bytes
* @param isLE - whether length and state words are encoded in little-endian
* @example
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
* ```ts
* import { _SHA1 } from '@noble/hashes/legacy.js';
* const hash = new _SHA1();
* hash.update(new Uint8Array([97, 98, 99]));
* hash.digest();
* ```
*/
export declare abstract class HashMD<T extends HashMD<T>> implements Hash<T> {
protected abstract process(buf: DataView, offset: number): void;
protected abstract get(): number[];
protected abstract set(...args: number[]): void;
abstract destroy(): void;
protected abstract roundClean(): void;
readonly blockLen: number;
readonly outputLen: number;
readonly canXOF = false;
readonly padOffset: number;
readonly isLE: boolean;
protected buffer: Uint8Array;
protected view: DataView;
protected finished: boolean;
protected length: number;
protected pos: number;
protected destroyed: boolean;
constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean);
update(data: TArg<Uint8Array>): this;
digestInto(out: TArg<Uint8Array>): void;
digest(): TRet<Uint8Array>;
_cloneInto(to?: T): T;
clone(): T;
}
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
* it as read-only because constructors copy words from it by index. */
export declare const SHA256_IV: TRet<Uint32Array>;
/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
* treat it as read-only because constructors copy words from it by index. */
export declare const SHA224_IV: TRet<Uint32Array>;
/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
* through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
* because constructors copy halves from it by index. */
export declare const SHA384_IV: TRet<Uint32Array>;
/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
* eight prime numbers. Exported as a shared table; callers must treat it as read-only because
* constructors copy halves from it by index. */
export declare const SHA512_IV: TRet<Uint32Array>;
//# sourceMappingURL=_md.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_md.d.ts","sourceRoot":"","sources":["src/_md.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAML,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,8BAAsB,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,YAAW,IAAI,CAAC,CAAC,CAAC;IAGlE,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAC/D,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAC/C,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB,SAAS,CAAC,QAAQ,CAAC,UAAU,IAAI,IAAI;IAErC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,SAAS;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAGvB,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;gBAEhB,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO;IAQjF,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA0BpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAkCvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;IAS1B,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAarB,KAAK,IAAI,CAAC;CAGX;AAED;;;GAGG;AAEH;;uEAEuE;AACvE,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAEtC,CAAC;AAEH;6EAC6E;AAC7E,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAEtC,CAAC;AAEH;;;wDAGwD;AACxD,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAGtC,CAAC;AAEH;;;gDAGgD;AAChD,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAGtC,CAAC"}
+202
View File
@@ -0,0 +1,202 @@
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
import { abytes, aexists, aoutput, clean, createView, } from "./utils.js";
/**
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
* Returns bits from `b` when `a` is set, otherwise from `c`.
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
* set the same bit.
* @param a - selector word
* @param b - word chosen when selector bit is set
* @param c - word chosen when selector bit is clear
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit choice primitive.
* ```ts
* Chi(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export function Chi(a, b, c) {
return (a & b) ^ (~a & c);
}
/**
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
* Returns bits shared by at least two inputs.
* @param a - first input word
* @param b - second input word
* @param c - third input word
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit majority primitive.
* ```ts
* Maj(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export function Maj(a, b, c) {
return (a & b) ^ (a & c) ^ (b & c);
}
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
* strings with partial-byte tails.
* @param blockLen - internal block size in bytes
* @param outputLen - digest size in bytes
* @param padOffset - trailing length field size in bytes
* @param isLE - whether length and state words are encoded in little-endian
* @example
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
* ```ts
* import { _SHA1 } from '@noble/hashes/legacy.js';
* const hash = new _SHA1();
* hash.update(new Uint8Array([97, 98, 99]));
* hash.digest();
* ```
*/
export class HashMD {
blockLen;
outputLen;
canXOF = false;
padOffset;
isLE;
// For partial updates less than block size
buffer;
view;
finished = false;
length = 0;
pos = 0;
destroyed = false;
constructor(blockLen, outputLen, padOffset, isLE) {
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
aexists(this);
abytes(data);
const { view, buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path only when there is no buffered partial block: `take === blockLen` implies
// `this.pos === 0`, so we can process full blocks directly from the input view.
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
clean(this.buffer.subarray(pos));
// we have less than padOffset left in buffer, so we cannot put length in
// current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
// `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
// the padding fill above, and JS will overflow before user input can make that half non-zero.
// So we only need to write the low 64 bits here.
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = createView(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
if (len % 4)
throw new Error('_sha2: outputLen must be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
// Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
// fresh bytes to the caller.
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to ||= new this.constructor();
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
// Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
// later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
}
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
* it as read-only because constructors copy words from it by index. */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
* treat it as read-only because constructors copy words from it by index. */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
* through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
* because constructors copy halves from it by index. */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
* eight prime numbers. Exported as a shared table; callers must treat it as read-only because
* constructors copy halves from it by index. */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map

Some files were not shown because too many files have changed in this diff Show More