如何在Kotlin中生成这些字节

时间:2019-08-22 21:29:51

标签: kotlin spring-security rabbitmq

我是Implementing RabbitMQ's Password Hashes。我通过复制Spring Security的StandardPasswordEncoder中的代码并对其进行改编来实现它。

package org.springframework.security.crypto.password

import org.springframework.security.crypto.codec.Utf8
import org.springframework.security.crypto.keygen.KeyGenerators
import org.springframework.security.crypto.util.EncodingUtils.concatenate
import java.security.MessageDigest
import java.util.Base64

class RabbitMqPasswordEncoder(
    algorithm: String = "SHA-256",
    secret: CharSequence = ""
): PasswordEncoder {
    private val digester =  MessageDigest.getInstance("SHA-256")
    private val saltGenerator = KeyGenerators.secureRandom(4)

    override fun encode(rawPassword: CharSequence): String {
        return encode(rawPassword, saltGenerator.generateKey())
    }

    override fun matches(rawPassword: CharSequence, encodedPassword: String): Boolean {
        throw UnsupportedOperationException("don't use this class for authentication")
    }

    fun encode(rawPassword: CharSequence, salt: ByteArray): String {
        val digest = digest(rawPassword, salt)
        return Base64.getEncoder().encodeToString(digest)
    }

    private fun digest(rawPassword: CharSequence, salt: ByteArray): ByteArray {
        val digest = digester.digest(
            concatenate(
                salt,
                Utf8.encode(rawPassword)
            )
        )
        return concatenate(salt, digest)
    }

}

我想使用文档示例转换对其进行测试。这样盐908D C60A和密码test12会创建base64编码的哈希  kI3GCqW5JLMJa4iX1lo7X4D6XbYqlLgxIs30+P6tENUV2POR

我遇到的问题是我不知道如何将盐(908D C60A)写到kotlin ByteArray中,以便将其传递给RabbitMqPasswordEncoder.encode

如果我做对了所有事情,并且文档正确,那么我相信该测试应该通过。我应该用???写什么?

    @Test
    fun encode() {
        val encoder = RabbitMqPasswordEncoder()
        val salt = byteArrayOf(???)
        val hash = encoder.encode("test12", salt)
        assertThat(hash).isEqualTo("kI3GCqW5JLMJa4iX1lo7X4D6XbYqlLgxIs30+P6tENUV2POR")
    }

注意:使用Kotlin 1.2

0 个答案:

没有答案