英文:
how to convert a number to base32 in java as per RFC-4648
问题
实际上我正在尝试在我的应用程序中使用TOTP,而谷歌身份验证器要求密钥以base32格式提供。这就是我试图将密钥转换为base32格式的原因。
假设我有一个数字 = 150820200825235。
这个链接的维基百科页面说明了RFC-4648是最常用的base32字母表。
下面是我尝试将数字转换为base32的Java代码:
long key=150820200825235L;
String base32Key = Long.toString(key,32);
System.out.println(base32Key);
现在它会打印以下输出:
> 495e87tgcj
其中包含了数字9,根据RFC-4648是无效的。
如何按照RFC-4648将数字转换为base32在Java中?
还有一件事,如果最常用的Base32字母表真的是按照RFC-4648的话,为什么Java不将其作为默认支持?或者是我理解/代码中有什么问题?
英文:
Actually I'm trying to use TOTP in my app and google authenticator requires the key to be in base32 format. This is the reason I'm trying to convert a key to base32 format
Let's say I have a number = 150820200825235.
This wikipedia page says that RFC-4648 is the most common base32 alphabet used.
Here's my java code where I'm trying to convert a number to base 32:
long key=150820200825235L;
String base32Key = Long.toString(key,32);
System.out.println(base32Key);
Now it is printing this as the output :
> 495e87tgcj
It contains 9 which is invalid according to RFC-4648.
how do I convert to base32 number as per RFC-4648 in java?
One more thing If the most widely used Base32 alphabet is really as per RFC-4648 then why doesn't java support it as default? or is something is wrong in my understanding/code ?
答案1
得分: 1
"Base32",如RFC-4648中定义,是一种将二进制数据("任意字节序列")编码为仅使用数字、大写字母和=
进行填充的ASCII文本的方法。您可以在Apache Commons Codec库中找到实现。
如果您从像150820200825235
这样的数字开始,想要将其转换为RFC 4648 base32格式,首先您需要决定如何将数字转换为字节序列。
例如,将long
值转换为字节的一种方法是使用DataOutputStream.writeLong
方法。该方法使用8个字节。使用此方法写入150820200825235L
并将结果字节编码为base32,您将得到AAAISK4QP3AZG===
。
英文:
"Base32" as defined in RFC-4648 is a way to encode binary data ("arbitrary sequences of octets") in ASCII text using only numbers, upper case letters, and =
for padding. You can find an implementation in the Apache Commons Codec library
If you start with a number like 150820200825235
and want to convert it into RFC 4648 base32, first you need to decide how to convert the number into a sequence of bytes.
Foe example, One way to convert a long
value into bytes is using the DataOutputStream.writeLong
method. This method uses 8 bytes. Using this method to write 150820200825235L and encoding the resulting bytes in base32 gives you AAAISK4QP3AZG===
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论