简体   繁体   中英

OAuth Consumer Secret Consumer Key generation in scala

Im trying to create consumer secret / key pairs in my scala play application but i cant seem to get it to work correctly. I have the following code

import org.apache.commons.codec.binary.Base64
import javax.crypto.{KeyGenerator, Mac, SecretKey}
import javax.crypto.spec.SecretKeySpec

def hmacSha1(baseString:String) : String = {
    val MAC_NAME = "HmacSHA1"
    val keygen = KeyGenerator.getInstance(MAC_NAME);
    val macKey = keygen.generateKey();
    val mac = Mac.getInstance(MAC_NAME);
    val secret = new SecretKeySpec(macKey.getEncoded(), mac.getAlgorithm());
    mac.init(secret);
    val digest = mac.doFinal(s.getBytes());
    val result= new binary.Base64().encode(digest)
    result.toString
}

but when i add in the baseString for something like "Anthony" I always get back a string that looks something like this

"[B@2008bf02" 

where as i was hoping to get something that looks more like this

“w/FdJ7y1qwe3HX/VmPiACTn01Zc=“ 

You are not converting the encoded byte array to a string correctly. The Base64 class has a method to help you. Just do this:

    mac.init(secret);
    val digest = mac.doFinal(s.getBytes());
    new binary.Base64().encodeBase64String(digest);
}

The more traditional way would be:

    mac.init(secret);
    val digest = mac.doFinal(s.getBytes());
    val result= new binary.Base64().encode(digest)
    new String(result, "ASCII");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM