From a1e25eefc2a2aaf2046fb20a4f26eb366e0e630a Mon Sep 17 00:00:00 2001 From: free will <2647778488@qq.com> Date: Tue, 9 Mar 2021 17:27:10 +0800 Subject: [PATCH] finished component: Nonce --- src/main/java/component/FreshnessPeriod.java | 2 +- src/main/java/component/Nonce.java | 104 +++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 src/main/java/component/Nonce.java diff --git a/src/main/java/component/FreshnessPeriod.java b/src/main/java/component/FreshnessPeriod.java index 4156b86..bb07c1c 100644 --- a/src/main/java/component/FreshnessPeriod.java +++ b/src/main/java/component/FreshnessPeriod.java @@ -82,7 +82,7 @@ public class FreshnessPeriod implements TlvComponentBase,InitialAble, IEncodingA return false; } - // 读取 FreshnessPeriod + // 读取 value long value=TLV.readNonNegativeInteger(block.getValue(),0,block.getLength().getVlIntValue2Int()); if(value<0){ return false; diff --git a/src/main/java/component/Nonce.java b/src/main/java/component/Nonce.java new file mode 100644 index 0000000..1a88535 --- /dev/null +++ b/src/main/java/component/Nonce.java @@ -0,0 +1,104 @@ +package component; + +import encoding.*; + +import java.util.Random; + +/* + * @Author: Wang Feng + * @Description: 表示一个随机数 TLV 组件 + * @Version: 1.0.0 + * @Date: 17:13 2021/3/9 + * @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室 + */ +public class Nonce implements TlvComponentBase,InitialAble, IEncodingAble { + // 成员变量 + private long nonce; + + // 成员函数 + public long getNonce() { + return this.nonce; + } + + public void setNonce(long nonce) { + this.nonce = nonce; + this.doInitial(); + } + + /** + * 刷新Nonce,随机生成一个数值传递给Nonce + */ + public void refreshNonce(){ + long randomLong=Math.abs(new Random().nextLong()); + this.setNonce(randomLong); + } + + // 接口实现-变量区 + private boolean initial=false; + + // 接口实现-方法区 + @Override + public void doInitial() { + initial=true; + } + + @Override + public boolean isInitial() { + return initial; + } + + /** + * 将 Nonce 线速编码为一个 TLV + * @param encoder + * @return + */ + @Override + public int wireEncode(Encoder encoder) { + int totalLength=0; + + // 编码 TLV-VALUE + int tmplen=encoder.prependNonNegativeInteger(this.nonce); + if(tmplen==0){ + return 0; + } + totalLength+=tmplen; + + // 编码 TLV-LENGTH + tmplen+=encoder.prependVarNumber(new VlInt(totalLength)); + if(tmplen==0){ + return 0; + } + totalLength+=tmplen; + + // 编码 TLV-TYPE + tmplen+=encoder.prependVarNumber(new VlInt(TLV.TlvNonce)); + if(tmplen==0){ + return 0; + } + totalLength+=tmplen; + + return totalLength; + } + + /** + * 从 TLV Block 中解码出一个 Nonce + * @param block + * @return + */ + @Override + public boolean wireDecode(Block block) { + // 检查 Type 是否正确 + if(!TLV.expectType(block.getTlvType(),new VlInt(TLV.TlvNonce))){ + return false; + } + + // 读取 value + long value=TLV.readNonNegativeInteger(block.getValue(),0,block.getLength().getVlIntValue2Int()); + if(value<0){ + return false; + } + this.setNonce(value); + + return true; + } +}