Skip to content

Commit 72a902f

Browse files
committed
impl: pixy secure code generator
Code Toolbox plugin should protect against authorization code interception attacks by making use of the PKCE security extension which involves a cryptographically random string (128 characters) known as code verifier and a code challenge - derived from code verifier using the S256 challenge method.
1 parent 52648a0 commit 72a902f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.coder.toolbox.oauth
2+
3+
import java.security.MessageDigest
4+
import java.security.SecureRandom
5+
import java.util.Base64
6+
7+
private const val CODE_VERIFIER_LENGTH = 128
8+
9+
/**
10+
* Generates OAuth2 PKCE code verifier and code challenge
11+
*/
12+
object PKCEGenerator {
13+
14+
/**
15+
* Generates a cryptographically random code verifier 128 chars in size
16+
* @return Base64 URL-encoded code verifier
17+
*/
18+
fun generateCodeVerifier(): String {
19+
val secureRandom = SecureRandom()
20+
val bytes = ByteArray(CODE_VERIFIER_LENGTH)
21+
secureRandom.nextBytes(bytes)
22+
23+
return Base64.getUrlEncoder()
24+
.withoutPadding()
25+
.encodeToString(bytes)
26+
.take(CODE_VERIFIER_LENGTH)
27+
}
28+
29+
/**
30+
* Generates code challenge from code verifier using S256 method
31+
* @param codeVerifier The code verifier string
32+
* @return Base64 URL-encoded SHA-256 hash of the code verifier
33+
*/
34+
fun generateCodeChallenge(codeVerifier: String): String {
35+
val digest = MessageDigest.getInstance("SHA-256")
36+
val hash = digest.digest(codeVerifier.toByteArray(Charsets.US_ASCII))
37+
38+
return Base64.getUrlEncoder()
39+
.withoutPadding()
40+
.encodeToString(hash)
41+
}
42+
}

0 commit comments

Comments
 (0)